Swift - 从 CollectionViewCell 中的 UIButton 推送到 ViewController [英] Swift - Push to ViewController from UIButton in CollectionViewCell

查看:20
本文介绍了Swift - 从 CollectionViewCell 中的 UIButton 推送到 ViewController的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图让我的按钮在点击时推送到新的视图控制器.我尝试了很多不同的方法,但它不会触发我链接到的功能.我还检查了图层的 3D 堆栈视图,按钮位于顶部且可点击,即使我检查背景颜色,它也没有被其他任何东西覆盖.

I am trying to make my button, when tapped, to push to a new View Controller. I've tried many different ways but it won't trigger the function that I have it linked to. I also checked the 3D stack view of my layers and the button is on top and clickable, even when I check the background color, it's not being covered by anything else.

有人对我做错了什么有任何想法吗?

Does anyone have any ideas to what I am doing wrong?

现在我试图让按钮在控制台中打印出句子,但是每当我按下它时,字符串都不会弹出,所以我还没有费心将它连接到视图控制器.

For now I am trying to make the button print out the sentence in the console, however whenever I press it, the string doesn't pop up, so I haven't bothered to connect it to the view controller yet.

此外,我正在编写这个没有故事板的应用程序.

Also, I am coding this app without storyboards.

下面是我的代码.

它在声明为 UICollectionViewCell 的 MainPageCell 类下

It is under the MainPageCell class declared as a UICollectionViewCell

private let playButton: UIButton = {
    let button = UIButton()
    button.setTitle("", for: .normal)
    button.backgroundColor = .clear
    button.translatesAutoresizingMaskIntoConstraints = false
    button.addTarget(self, action: #selector(MainPageCell.buttonTapped), for: .touchUpInside)
    return button
}()

@objc func buttonTapped() {
    print("I PRESSED THE BUTTON")
}

推荐答案

这行错误:

button.addTarget(self, action: #selector(MainPageCell.buttonTapped), for: .touchUpInside)

您不能将 self 指定为属性声明初始值设定项中的操作目标,因为由 self 指定的实例尚不存在.没有错误或警告(我认为这是一个错误),但从未调用 action 方法.

You cannot assign self as the action target in a property declaration initializer, because the instance designated by self does not exist yet. There is no error or warning (I regard that as a bug), but the action method is never called.

将该作业移到别处并重写,如下所示:

Move that assignment elsewhere and rewrite it, like this:

self.playButton.addTarget(self, action: #selector(MainPageCell.buttonTapped), for: .touchUpInside)

这篇关于Swift - 从 CollectionViewCell 中的 UIButton 推送到 ViewController的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆