Автоматическое изменение размера представления коллекции и настройка повторяющегося фона - PullRequest
0 голосов
/ 06 февраля 2020

Я использую представление коллекции для загрузки данных из API. Здесь я хочу расширить размер высоты представления коллекции вместо прокрутки в представлении коллекции. А также необходимо повторить фоновое изображение в соответствии с высотой представления коллекции. Вот макет android, и я хочу разработать аналогичный этому. Нажмите здесь

import UIKit import Nuke import SVProgressHUD import JSONJoy class HomeViewController: UIViewController {

@IBOutlet weak var categoryCollection: UICollectionView!
@IBOutlet weak var tabbar: UITabBar!



var sectors:[Sector] = []
var timer = Timer()
var counter = 0
var selectedSector = ""
var selectedSectorName = ""
var webService = ApiService()
let plist = PlistHelper()
override func viewDidLoad() {
    super.viewDidLoad()

    self.categoryCollection.dataSource = self
    self.categoryCollection.delegate = self
    for item in tabbar.items ?? []{
        item.image = item.image?.withRenderingMode(.alwaysOriginal)

    }
    UITabBarItem.appearance().setTitleTextAttributes([NSAttributedString.Key.foregroundColor: UIColor.white], for: .normal)
    UITabBarItem.appearance().setTitleTextAttributes([NSAttributedString.Key.foregroundColor: UIColor.black], for: .selected)
        listSectors()

    self.categoryCollection.backgroundColor = UIColor(patternImage: UIImage(named: "bg")!)

}
override func viewWillAppear(_ animated: Bool) {
    listbanners()

}
override func viewWillDisappear(_ animated: Bool) {
    self.timer.invalidate()
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if(segue.identifier == "sectors"){
        let vc  = segue.destination as! SectorsViewController
        vc.sectorCode = selectedSector
        vc.sectorName = selectedSectorName
    }
}



func listSectors(){

    webService.listSectors({ (sectors, message, status) in

        if(status){
            if let resData = sectors.arrayObject {
                do{
                    for data in resData{
                        self.sectors.append(try Sector(JSONLoader(data)))

                    }

                    DispatchQueue.main.async {
                        self.categoryCollection.reloadData()

                    }

                }
                catch let error {
                    print("JSonJoyError:\(error)")
                }
            }
        }
    })
}

} расширение HomeViewController: UICollectionViewDelegate, UICollectionViewDataSource {

func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    if(collectionView == bannerCollection){
        return banners.count
    }
    else {
        return sectors.count
    }

}

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let options = ImageLoadingOptions(placeholder: UIImage(named: "bannerPlaceholder"),transition: .fadeIn(duration: 0.33))
    if(collectionView == bannerCollection){
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! DataCollectionViewCell


    Nuke.loadImage(with: URL(string: banners[indexPath.row].ImageUrl ?? "")!, options: options, into:cell.img)

    return cell
    }
    else{

            let cell = categoryCollection.dequeueReusableCell(withReuseIdentifier: "catCell", for: indexPath) as! catogeryCollectionViewCell
            Nuke.loadImage(with: URL(string: sectors[indexPath.row].ImageUrl ?? "")!, options: options, into:cell.photoImageView)


                return cell
    }
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
    if(collectionView == categoryCollection){
        selectedSector = sectors[indexPath.row].Code ?? "FOOD"
        selectedSectorName = sectors[indexPath.row].Name ?? "FOOD"
        self.performSegue(withIdentifier: "sectors", sender: self)
    }
}

}

расширение HomeViewController: UICollectionViewDelegateFlowLayout {

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
    return UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
}

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
    if(collectionView == bannerCollection){
    let size = bannerCollection.frame.size

        return CGSize(width: size.width, height: size.height - 10)
    }
    else{
        let size = categoryCollection.frame.size
          print("size\(size)")
        return CGSize(width: (size.width / 2) - 8, height:120)
    }
}

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
    return 30
}

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
    return 0.0
}

}

1 Ответ

1 голос
/ 06 февраля 2020

Следующие шаги помогут вам увеличить высоту представления вашей коллекции в соответствии с данными.

  1. Создать выход ограничения высоты.

  2. После загрузки данных в представление коллекции с задержкой 0,2 se c в главном потоке, константа Set Height Constraint = высота размера содержимого представления коллекции.

...