UICollectionView indexPath.row奇怪的行为

时间:2016-09-27 10:17:24

标签: ios swift uicollectionview nsindexpath

滚动我的一个collectionView时,我遇到了一个奇怪的问题。当我正在打印时indexPath.row从0..6开始正常,但最后indexPath.row为3,然后如果我向后滚动它或者用excbadadress崩溃或以随机顺序打印1,2,4 。我假设我的代码中有错误但实际上不明白它在哪里。 这是我的代码: VC:

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: IndexPath) -> CGSize {
    if collectionView == mainEventsCollectionView {
        return CGSize(width: UIScreen.main.bounds.width - 40, height: 180)
    } else {
        return CGSize(width: 150, height: 200)
    }
}

func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    if collectionView == mainEventsCollectionView {
        return 3
    } else {
        return 7
    }
}

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    if collectionView == mainEventsCollectionView {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "mainEventsCell", for: indexPath) as! MainEventCollectionViewCell
        cell.eventTitle.text = "Hello world".uppercased()
        cell.setupCell()
        return cell
    } else {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "importantEventsCell", for: indexPath) as! ImportantEventsCollectionViewCell
        print(indexPath.row)
        cell.setupCell()
        return cell
    }
}

细胞:

required init?(coder aDecoder: NSCoder) {
    super.init(coder: aDecoder)
    self.roundCorners(.allCorners, radius: 6, borderColor: .clear, borderWidth: 0)
}

func setupCell() {
    self.content.backgroundColor = colorWithAlpha(.black, alpha: 0.7)
    self.eventDate.textColor = .white
    self.eventTime.textColor = .white
    self.eventName.textColor = .white
    if self.content.layer.sublayers!.count > 3 {
        self.content.layer.sublayers!.removeLast()
    }
    if self.eventDate.text == "Today" {
        self.content.backgroundColor = .clear
        DispatchQueue.main.async(execute: {
            self.content.drawGradient(colors: [UIColor(red: 250/255, green: 217/255, blue: 97/255, alpha: 0.7).cgColor, UIColor(red: 255/255, green: 135/255, blue: 67/255, alpha: 0.7).cgColor], locations: [0, 1])
        })
        self.eventDate.textColor = .black
        self.eventTime.textColor = .black
        self.eventName.textColor = .black
    }
}

1 个答案:

答案 0 :(得分:0)

好的,问题是我尝试将渐变应用于UIView,其中包含元素(UILables)。我要做的是向UIView添加一个子视图并对其应用渐变。