Cell 里面的 Button 获取不到

头发还没秃a 2016-02-24 03:17:58

如图:我在添加了两个Cell,每个Cell里面有一个 Button, 两个 Button 的 Tag都设置为1,但是在代码里面
let cityLocationButton = collectionCell!.viewWithTag(1) as! UIButton
获取 Button 的时候,第二个 Cell 的 Button 获取不到,就算把第二个 Button 的 Tag 设置为2也获取不到,请问是怎么回事呢?下面贴上我的代码:

var collectionCell: UICollectionViewCell?
var cellID: String?
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell{
if indexPath.row > 0{
cellID = "collectionCellCityName"
}else{
cellID = "collectionCellLocation"
}
collectionCell = collectionView.dequeueReusableCellWithReuseIdentifier(cellID!, forIndexPath: indexPath) as UICollectionViewCell
let cityLocationButton = collectionCell!.viewWithTag(1) as! UIButton
if indexPath.row > 0{
cityLocationButton.setBackgroundImage(UIImage(named: "citylocation_city"), forState: UIControlState.Normal)
cityLocationButton.setTitle(cities[indexPath.row-1], forState: UIControlState.Normal)
}
cityLocationButton.tag = indexPath.row
//添加点击事件
cityLocationButton.addTarget(self, action: "clickForCityName:", forControlEvents: UIControlEvents.TouchUpInside)

return collectionCell!
}
...全文
143 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
头发还没秃a 2016-02-25
  • 打赏
  • 举报
回复
好吧,我自己解决了
头发还没秃a 2016-02-24
  • 打赏
  • 举报
回复
没人知道这个问题怎么解决么?
头发还没秃a 2016-02-24
  • 打赏
  • 举报
回复
找到问题了,是因为我的第二个 Cell 的 Button继承了我重写的一个类:
import UIKit

class CollectionItemClickEffect : UIButton {
    
    override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
        setBackgroundImage(UIImage(named: "citylocation_city_touchdown"), forState: UIControlState.Normal)
    }
    
    override func touchesCancelled(touches: Set<UITouch>?, withEvent event: UIEvent?) {
        UIButton.animateWithDuration(0.15, animations: { () -> Void in
            self.setBackgroundImage(UIImage(named: "citylocation_city"), forState: UIControlState.Normal)
        })
    }
    
    override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) {
        UIButton.animateWithDuration(0.15, animations: { () -> Void in
            self.setBackgroundImage(UIImage(named: "citylocation_city"), forState: UIControlState.Normal)
        })
    }
}
这个类只定义了 Button的点击效果,为什么会连点击事件都失去了呢?有哪位大大知道问题出在哪么?

29,027

社区成员

发帖
与我相关
我的任务
社区描述
主要讨论与iOS相关的软件和技术
社区管理员
  • iOS
  • 大熊猫侯佩
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧