ios - 通过主视图 Controller 与 UICollectionViewCell 中的按钮交互

标签 ios swift xcode button uicollectionview

我正在制作一个应用程序,允许用户在我的家庭 ViewController 类中实现的 Collection View 中“固定”某些元素。要固定元素,用户必须访问属于我的 WordCell (UICollectionViewCell) 类的按钮。但是,当我尝试从我的主视图 Controller 按下按钮时,没有任何 react 。
以下是所有相关代码和屏幕截图:

右侧的星号是 CollectionViewCell 内的按钮,我希望用户能够插入主视图。
下面是我的 ViewController 类中的所有相关代码。我正在使用委托(delegate)传递被压入我的家庭类 ViewController 的单元格。我还计划将来在单元格(UICollectionCellView)类和 ViewController 之间来回传递更多数据。

extension ViewController: UICollectionViewDataSource{
//......
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let wordCell = collectionView.dequeueReusableCell(withReuseIdentifier: wordCellReuseID, for: indexPath) as! WordCell
        
        wordCell.delegate = self
        
        wordCell.configure(word: tempWords[indexPath.item])
        return wordCell
    }
//......
}

extension ViewController: WordCellDelegate{
    func star(wasPressedOnCell: WordCell){
        print("touched")
        
        if(wasPressedOnCell.isStarred){ //if the button has already been starred, unstar it
            wasPressedOnCell.starButton.setImage(UIImage(named: "unfilled_star.png"), for: .normal)
            wasPressedOnCell.isStarred = false
        }
        
        else{ //else, star the button
            wasPressedOnCell.starButton.setImage(UIImage(named: "filled_star.png"), for: .normal)
            wasPressedOnCell.isStarred = true
        }
    }
}
这是我的类中符合 UICollectionCellView 的相关代码:
//delegate setup for home class
protocol WordCellDelegate: class{
    func star(wasPressedOnCell cell: WordCell) //parameter: cell that was pressed
}

//........

//button setup
starButton = UIButton()
        starButton.setImage(UIImage(named: "unfilled_star.png"), for: .normal)
        starButton.translatesAutoresizingMaskIntoConstraints = false
        starButton.addTarget(self, action: #selector(starred), for: .touchUpInside)
        contentView.addSubview(starButton)

//......

//button objective function
@objc func starred(){
        print("touched")
        
        delegate?.star(wasPressedOnCell: self)
        
        //starredTapAction?() //chained back to main view controller
    }

但是,当我尝试在主视图 Controller 屏幕上按下星号时,不会调用 UICollectionCellView 类中的 objc 函数。我从以前的帖子中了解到,这很可能是由于类的层次结构以及哪个 View 控制哪些对象,但我还没有找到解决这个问题的方法。我不确定需要更改什么,以便可以通过 Collection View 按下集合单元格内的按钮。
如果您需要更多信息,请告诉我,感谢您阅读这篇文章!

最佳答案

请禁用 Collection View 的单元格选择,您的按钮触摸事件将触发,基本上一次您可以使用 Collection View 选择方法或按钮操作方法

关于ios - 通过主视图 Controller 与 UICollectionViewCell 中的按钮交互,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66842700/

相关文章:

objective-c - 如何向方法添加可视化文档

iphone - 检查单词在数组中是否有效

ios - 进入后台时释放内存

ios - Monotouch Ipad3 retina 无法以全分辨率运行

ios - 检查旧版本的应用程序中是否使用了 NSUserDefaults

ios - 如何让动画重复一定次数?

ios - Tableview重新加载数据将数字恢复为默认值

ios - Realm : How to delete object from RLMArray?

ios - 编辑期间阻塞的字段。 ( swift - iOS)

ios - Xcode 6 Storyboard无法居中