gpt4 book ai didi

swift - 如何让 UIButton 按下以在 Swift 中的 UICollectionViewCell 中工作?

转载 作者:搜寻专家 更新时间:2023-11-01 05:44:11 24 4
gpt4 key购买 nike

所以这是 Swift 中的 tvOS 项目。我有一个自定义 UICollectionViewCell,其中一个按钮作为其 subview 之一。我向按钮添加了一个目标以允许它解释点击。这是相关代码的简化版本

class CustomCell: UICollectionViewCell {
var button:UIButton!

override init(frame: CGRect) {
super.init(frame: frame)

button = UIButton(...) // Button is initialized with a frame
button.userInteractionEnabled = true
button.enabled = true
button.addTarget(self, action: "pressed:", forControlEvents: .PrimaryActionTriggered)
contentView.addSubview(button)
}

func pressed(sender: UIButton!) {
print("button pressed!")
}
}

出于某种原因,它从未打印出我的消息。我尝试将“pressedEnded”添加到单元格类中以查看它是否得到任何东西并被调用

func pressesEnded(presses: Set<UIPress>, withEvent event: UIPressesEvent?) {
// If I put a breakpoint here it's reached
}

有什么建议吗?我在模拟器中运行的时候按钮可以获取焦点,所以我不知道为什么它不能获取任何事件

最佳答案

所以,我想出了解决这个问题的方法,尽管它在某种程度上是一种变通方法。基本上对于 UICollectionView,我需要确保单元格不能获得焦点。

接下来,我之前在 CustomCell 中有 didUpdateFocusInContext。当 cell 时,这实际上是为按钮设置动画,但当我检查按钮时,它从未获得焦点。我猜这是拦截它。因此,我从 CustomCell 中删除了该函数,而是在我的文件底部添加了该函数作为 UIButton 的扩展。

这也可以通过创建 UIButton 的子类并改为使用它来完成,但这会减少代码(这可能是理想的方式)。所以完整的代码看起来像:

class MyCollection: UICollectionView, UICollectionViewDelegate {
// Need initializer functions as well as functions for creating CustomCell's. They're omitted because they're not relevant to the answer

func collectionView(collectionView: UICollectionView, canFocusItemAtIndexPath indexPath: NSIndexPath) -> Bool {
return false
}
}

class CustomCell: UICollectionViewCell {
var button:UIButton!

override init(frame: CGRect) {
super.init(frame: frame)

button = UIButton(...) // Button is initialized with a frame
button.userInteractionEnabled = true
button.enabled = true
button.addTarget(self, action: "pressed:", forControlEvents: .PrimaryActionTriggered)
self.addSubview(button)
}

func pressed(sender: UIButton!) {
print("button pressed!")
}
}

extension UIButton {
override public func didUpdateFocusInContext(context: UIFocusUpdateContext, withAnimationCoordinator coordinator: UIFocusAnimationCoordinator) {
super.didUpdateFocusInContext(context, withAnimationCoordinator: coordinator)

if self.superview is CustomCell { // This ensures that all UIButtons aren't affected
if context.nextFocusedView == self {
// Perform actions for when UIButton is focused
}else {
// Perform actions for when UIButton loses focus
}
}
}
}

关于swift - 如何让 UIButton 按下以在 Swift 中的 UICollectionViewCell 中工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34750236/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com