gpt4 book ai didi

ios - 将父类作为目标添加到 UIButton

转载 作者:行者123 更新时间:2023-11-30 13:06:28 24 4
gpt4 key购买 nike

我有一个 UIButton likeButton,它将在 .TouchUpinside 上调用 likeBtnClicked

likeButton.addTarget(self.superview, action: "likeBtnClicked:", forControlEvents: UIControlEvents.TouchUpInside)

这工作正常,但有警告

"No method declared with Objective-C selector".

如果 likeButton 在一个类(例如 MyClass)中实现,那么我会将其替换为

likeButton.addTarget(Myclass, action: #selector(Myclass.likeBtnClicked), forControlEvents: UIControlEvents.TouchUpInside)

但是如何使其适用于多个想要使用“likeButton”而没有任何警告的类(viewControllers)?这个问题对于 UITapGestureRecognizer 也同样适用。

这里是示例代码:

import Foundation

class SubClass: UIView {

var likeButton = UIButton(frame: CGRectMake(0,0,100,50))

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

addSubview(likeButton)
likeButton.addTarget(self.superview, action: "likeBtnClicked:", forControlEvents: UIControlEvents.TouchUpInside)
}

required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}

class SuperClassA: UIView {

let viewHavingBtn = SubClass(frame: CGRectMake(0,0,300,500))

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

addSubview(viewHavingBtn)
}

func likeBtnClicked(sender: AAButton) {
print(sender.tag)
}

required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}

class SuperClassB: UIView {

let viewHavingBtn = SubClass(frame: CGRectMake(0,0,300,500))

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

addSubview(viewHavingBtn)
}

func likeBtnClicked(sender: AAButton) {
print(sender.tag)
}

required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}

最佳答案

请按照以下步骤操作:

1] 在父类(super class)中声明一个 UIButton 对象

2]初始化该按钮并在父类(super class)初始化方法中将目标添加到该按钮

3]在父类(super class)中定义触摸事件的操作方法

4]将该按钮添加为子类中的 subview 以显示按钮

5] 在要处理按钮触摸的子类中重写父类(super class)中的按钮操作方法实现。

关于ios - 将父类作为目标添加到 UIButton,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39306278/

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