UICollectionView使用reloadData()方法之后,Cell 里面的控件报错找不到

iOS 码拜 8年前 (2016-01-31) 1568次浏览
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell{
        NSLog("\(indexPath.row)")
        let collectionCell = collectionView.dequeueReusableCellWithReuseIdentifier("collectionCellLocation", forIndexPath: indexPath) as UICollectionViewCell
        
        let cityLocationButton = collectionCell.viewWithTag(1) as! UIButton
        let autoLocationButton = collectionCell.viewWithTag(2) as! UIButton
        if indexPath.row > 0 {
            NSLog("1111111")
            autoLocationButton.hidden = true
            cityLocationButton.setTitle(searchCityList[indexPath.row-1], forState: UIControlState.Normal)
        }else{
            cityLocationButton.hidden = true
        }
        
        //添加手动定位点击事件
        cityLocationButton.tag = indexPath.row
        let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: "clickForCityName:")
        cityLocationButton.addGestureRecognizer(tapGestureRecognizer)
        //添加自动定位点击事件
        autoLocationButton.tag = indexPath.row
        autoLocationButton.addTarget(self, action: "clickAutoLocation:", forControlEvents: UIControlEvents.TouchUpInside)
        
        return collectionCell
    }

刚进来的时候可以正常显示控件,但是reloadData()之后,就报错:

let cityLocationButton = collectionCell.viewWithTag(1) as! UIButton

这一行显示错误信息是:fatal error: unexpectedly found nil while unwrapping an Optional value
望高手们解答

解决方案:40分
你这种设计方式不对
在你这种方式里button的tag变成有两个作用,1.根据tag找到button视图 2.根据tag标识当前记录在数据源中的位置
所以你这里的tag是冲突的.
你应该将按钮的点击事件放在你自定的cell里,然后把点击cell要做的事情通过协议让数据源所在的类来实现.

CodeBye 版权所有丨如未注明 , 均为原创丨本网站采用BY-NC-SA协议进行授权 , 转载请注明UICollectionView使用reloadData()方法之后,Cell 里面的控件报错找不到
喜欢 (0)
[1034331897@qq.com]
分享 (0)