我有一个UIButton likeButton
,会在likeBtnClicked
上致电.TouchUpinside
likeButton.addTarget(self.superview, action: "likeBtnClicked:", forControlEvents: UIControlEvents.TouchUpInside)
这样可以正常但有警告
“没有使用Objective-C选择器声明的方法”。
如果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")
}
}
答案 0 :(得分:0)
请按照以下步骤操作:
1]在超类中声明一个UIButton对象
2]初始化该按钮并在超类初始化方法中将目标添加到该按钮
3]为超类中的触摸事件定义动作方法
4]将该按钮添加为子类中的子视图以显示按钮
5]覆盖要处理按钮触摸的子类中超类的按钮动作方法实现。