I have a UIButton
that I created programmatically. I have added a target to it, but it doesn't seem to be running properly. Here is my code (This is a custom class of UIView
):
override init(frame: CGRect) {
super.init(frame: frame)
print("targets:")
print(clickButton.allTargets())
clickButton.addTarget(self, action: #selector(self.clickPicture), for: .touchUpInside)
print("targets:")
print(clickButton.allTargets())
}
This is what prints as a result:
As you can see, adding a target to my button does not make a difference. Here is the clickPicture
function:
func clickPicture() {
print("clickpicture")
}
Again, this does not print. Does anybody know how to fix this error? Thanks!
Edit:
Definition for clickButton
(in my custom class):
var clickButton = UIButton()
Other properties defined in the init
:
clickButton.frame.size = CGSize(width: 100, height: 100)
clickButton.layer.cornerRadius = clickButton.frame.size.width / 2
clickButton.layer.borderColor = UIColor.white().cgColor
clickButton.layer.borderWidth = 2.5
clickButton.layer.backgroundColor = shadeColor.cgColor
clickButton.center.x = self.center.x
clickButton.center.y = self.frame.size.height - clickButton.frame.size.height// + 40
clickButton.addTarget(self, action: #selector(self.clickPicture), for: .touchUpInside)
self.addSubview(clickButton)
The button was not on top of the custom view when I instantiated it. I changed its position, and it worked fine.
You have to change this line
clickButton.addTarget(self, action: #selector(self.clickPicture), for: .touchUpInside)
to this
clickButton.addTarget(self, action: #selector(YourClassName.clickPicture), forControlEvents: UIControlEvents.TouchUpInside)
And the method should be
func clickPicture() {
print("clickpicture")
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.