如何快速访问功能数组?

时间:2019-02-03 08:38:59

标签: ios swift

我是新来的。 我在nib文件中做了一个collectionview,在主视图控制器中有一个subview。 我想在collectionview中显示数组,但我不能。 首先,我制作一天的模型:

struct Days {    
    let day: String
    let Image: String
    let temp: Double
}

然后在daycell中

class DayCell: UICollectionViewCell {
    @IBOutlet weak var lblDay: UILabel!
    @IBOutlet weak var imgWeather: KBImageView!
    @IBOutlet weak var lblTemp: UILabel!    
    func updateViews(day: Days) {
        lblDay.text = day.day
        imgWeather.setImageWithKingFisher(url: day.Image)
        lblTemp.text = String(day.temp)
    }
}

然后在公共类中,我使用alamofire获取json数据并将其解码并将其放入我的模型中:

public class Publics {
    static let instance = Publics()  

func showInfo(code: String, completion: @escaping ([Days]) -> Void)  {


    let DaysUrl = "http://api.openweathermap.org/data/2.5/forecast?id=\(code)&appid=3e28385cde03f6ee26c83b629ca274cc"
       Alamofire.request(DaysUrl, method: .get, parameters: nil, encoding: URLEncoding.httpBody).responseJSON { response in
            if let data = response.data {
                do {
                    self.myJson = try JSONDecoder().decode(JsonForecast.Response.self, from: data)                   

                    let counter = (self.myJson?.list.count)! - 1

                    let myDay1 = self.myJson?.list[counter-32]
                    let myDay2 = self.myJson?.list[counter-24]
                    let myDay3 = self.myJson?.list[counter-16]                   

                    let weekDay1 = self.getDate(date: self.getDayOfWeek((myDay1?.dt_txt)!)!)
                    let weekDay2 = self.getDate(date: self.getDayOfWeek((myDay2?.dt_txt)!)!)
                    let weekDay3 = self.getDate(date: self.getDayOfWeek((myDay3?.dt_txt)!)!)

                   let DaysArray = [
                        Days(day: weekDay1, Image: (myDay1?.weather[0].icon)!, temp: (myDay1?.main?.temp)!) ,
                        Days(day: weekDay2, Image: (myDay2?.weather[0].icon)!, temp: (myDay2?.main?.temp)!) ,
                        Days(day: weekDay3, Image: (myDay3?.weather[0].icon)!, temp: (myDay3?.main?.temp)!)
                    ]
                    completion(DaysArray)
                } catch {
                    print(error)
                }
            }
        }
    }

直到这里我没有问题,但是现在我想在collectionview中显示DaysArray,但是我不能,并且我的collectionview类如下:

class DayCollection: UIView, UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {

    @IBOutlet var contentView: UIView!
    @IBOutlet weak var collectionDay: UICollectionView!
    var days = [Days]()


    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "DayCell", for: indexPath) as! DayCell

        Publics.instance.showInfo(code: "112931") { result in
            self.days = result
            print(self.days)
            DispatchQueue.main.async {
                self.collectionDay.reloadData()
            }
        }
        let day = days[indexPath.item]
        cell.updateViews(day: day)

            return cell

    }

    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return days.count
    }

    override func awakeFromNib() {
        super.awakeFromNib()

        self.collectionDay.dataSource = self
        self.collectionDay.delegate = self
        self.collectionDay.register(UINib(nibName: "DayCell", bundle: nil), forCellWithReuseIdentifier: "DayCell")

    }
}

在mainVC类中我应该做什么? (也许我应该从协议委托中使用还是不使用?)

1 个答案:

答案 0 :(得分:2)

首先,如果要在结构中具有常量,请将其声明为 constants private(set)很可怕。

struct Days {    
    let day: String
    let dImage: String
    let temp: Double 
}

并且从不将结构成员声明为隐式未包装的可选对象,这些可选对象在init方法中使用非可选值进行初始化。无论如何都不需要在结构中使用init方法。


您必须添加完成处理程序

public func showInfo(code: String, completion: @escaping ([Days]) -> Void)  {

...

let daysArray = [
   Days(day: weekDay1, Image: (myDay1?.weather[0].icon)!, temp: (myDay1?.main?.temp)!) ,
   Days(day: weekDay2, Image: (myDay2?.weather[0].icon)!, temp: (myDay2?.main?.temp)!) ,
   Days(day: weekDay3, Image: (myDay3?.weather[0].icon)!, temp: (myDay3?.main?.temp)!)
]
completion(daysArray)
}

然后在集合视图的类中添加一个数据源数组

var days = [Days]() 

并获取数据

Publics.instance.showInfo(code: "Foo") { result in
   self.days = result
   DispatchQueue.main.async {
       self.collectionDay.reloadData()
    }
}

return days.count中的numberOfItemsInSection

进一步用力解开细胞

let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "DayCell", for: indexPath) as! DayCell

如果代码崩溃,则说明您犯了一个设计错误。使用可选绑定,代码不会崩溃,但是您什么也看不到,也不知道为什么

还有一天

let day = days[indexPath.item]
cell.updateViews(day)