【发布时间】:2015-03-10 23:06:59
【问题描述】:
我检查了类似的主题,但没有一个对我有帮助。基本上,我写了一个自定义的UICollectionViewCell,在collectionView 中,当我点击其中任何一个时,didSelectItemAtIndexPathmethod 不会被触发。
我重写了我的代码以使用标准UICollectionViewCell,然后它就可以工作了。任何人都可以帮助我解决我应该覆盖/更改的内容吗?
自定义单元格:
class UICollectionViewCellWithButton: UICollectionViewCell {
var button = UIButton();
override init(frame: CGRect) {
super.init(frame: frame);
button = UIButton.buttonWithType(UIButtonType.System) as UIButton;
button.setTitle("", forState: UIControlState.Normal);
button.frame = CGRectMake(0, 0, 50, 50);
self.addSubview(button);
}
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder);
}
/* override func hitTest(point: CGPoint, withEvent event: UIEvent?) -> UIView?{
return self;
}*/
}
集合视图:
class StartNodeViewController: UICollectionViewController, UICollectionViewDelegate {
var numberOfNodes = Int();
private let reuseIdentifier = "Cell";
var cellColor = true;
var counter = 1;
override func viewDidLoad() {
super.viewDidLoad();
self.navigationItem.title="Select start node";
self.collectionView.registerClass(UICollectionViewCellWithButton.self, forCellWithReuseIdentifier: "Cell");
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
// 1
return 1;
}
override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
// 2
return numberOfNodes;
}
override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCellWithButton {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath) as UICollectionViewCellWithButton;
cell.button.setTitle(counter.description, forState: UIControlState.Normal);
cell.backgroundColor = UIColor.whiteColor();
counter++;
return cell;
}
override func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
//super.collectionView(collectionView, didSelectItemAtIndexPath: indexPath);
(collectionView.cellForItemAtIndexPath(indexPath) as UICollectionViewCellWithButton).button.setTitle("0", forState: UIControlState.Normal);
}
}
此时代码可能有点混乱,因为我尝试了我找到的任何东西。
【问题讨论】:
-
细胞有多大?您的按钮是否覆盖整个事物并拦截触摸?
-
你是对的!按钮肯定会覆盖它。有什么办法可以让按钮放弃触摸拦截?
-
你为什么要他们这样做?你想让按钮做什么,你想让单元格选择做什么?两种不同的东西?
-
该代码目前用作各种占位符。我想要做的是在触摸该按钮或单元格本身时触发 didSelectItemAtIndexPath,没关系
-
或者,只是去掉按钮。如果你想让它做和单元格选择一样的事情,它的目的是什么?
标签: ios swift uicollectionview