我正在创建一个应用程序,其中使用了 3 个按钮网格。 我为此使用了 UICollectionViewController 并将按钮添加到 UICollectionViewCell 还为每个按钮单击事件添加目标 下面的代码
override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell : CollectionViewCell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath) as! CollectionViewCell
if indexPath.row == 0 {
cell.btn.addTarget(self, action: "first", forControlEvents: UIControlEvents.TouchUpInside)
cell.btn.setTitle("1st", forState: .Normal)
}else if indexPath.row == 1 {
cell.btn.addTarget(self, action: "second", forControlEvents: UIControlEvents.TouchUpInside)
cell.btn.setTitle("2nd", forState: .Normal)
}else if indexPath.row == 2 {
cell.btn.addTarget(self, action: "third", forControlEvents: UIControlEvents.TouchUpInside)
cell.btn.setTitle("3rd", forState: .Normal)
}
}
每当单击按钮时, View Controller 都会导航到另一个 View Controller 代码
var destinationViewController : UIViewController!
func third(){
destinationViewController = storyboard?.instantiateViewControllerWithIdentifier("AddInventory") as! UIViewController
navigationController?.pushViewController(destinationViewController, animated: true)
}
但是点击任何按钮都会导航到同一个 View Controller 因为我使用段 View Controller ,并且对于特定的索引,将显示不同的 View ,所以我必须检查从 Collection View 中选择了哪个按钮 我使用标签进行检查
cell.btn.tag = indexPath.row
但它不起作用 我无法访问标签
简而言之,我的问题是如何检查在推送到另一个 View Controller 时单击了哪个按钮(来自 collectionview) 提前致谢
最佳答案
也许这对你有帮助:
override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell : CollectionViewCell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath) as! CollectionViewCell
cell.btn.tag = indexPath.row
cell.btn.addTarget(self, action: "buttonClicked", forControlEvents: UIControlEvents.TouchUpInside)
}
func buttonClicked(sender: UIButton?) {
let tag = sender.tag
let destinationViewController = storyboard?.instantiateViewControllerWithIdentifier("AddInventory") as! DestinationViewController
destinationViewController.fromTag = tag
navigationController?.pushViewController(destinationViewController, animated: true)
}
关于ios - 如何知道从另一个 View Controller 中的 UICollectionViewController 按下了哪个按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32067252/