我有一个名为Icons的自定义UIView。除了一件事,现在一切都很好。我遇到的问题是能够设置用户交互工作,或者让我班上的按钮工作。当我向按钮添加一个目标时,我得到一个错误,崩溃一切,并且用户交互到视图,我得不到任何响应。
class Icons: UIView {
let xUnit = UIScreen.mainScreen().bounds.width/20
let yUnit = UIScreen.mainScreen().bounds.height/30
var name: String = String()
var image: UIImage = UIImage()
let font = UIFont(name: "HelveticaNeue-Thin", size: 16.0)!
override init(frame: CGRect) {
super.init(frame: frame)
self.userInteractionEnabled = true
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func addCustomView(name:String, image: UIImage ){
let label: UILabel = UILabel()
label.frame = CGRectMake(0, 1.5*xUnit, 3.4*xUnit, 2.7*xUnit)
label.textAlignment = NSTextAlignment.Center
label.font = font
label.text = name
self.addSubview(label)
let btn: UIButton = UIButton()
btn.frame=CGRectMake(0.3*xUnit, 0, 2.5*xUnit, 2.5*xUnit)
btn.setImage(image, forState: .Normal)
self.addSubview(btn)
}
}
这是我正在尝试连接的课程,这是一个完全不同的课程
func tapSettings(tapGestureRecognizer: UITapGestureRecognizer){
let touchPoint = tapGestureRecognizer.locationInView(self.view)
if(CGRectContainsPoint(settings.frame, touchPoint)){
print("hi")
}
}
当我尝试将其连接到按钮时我说:
btn.addTarget(self,action: #selector(HomeScreen.tapSettings))
当我尝试将其连接到视图时,我说:
let settingsTouch = UITapGestureRecognizer(target: self, action: #selector(HomeScreen.tapSettings))
settingsTouch.numberOfTapsRequired = 1
settingsTouch.numberOfTouchesRequired = 1
self.view.addGestureRecognizer(settingsTouch)
答案 0 :(得分:0)
试试这个
btn.addTarget(HomeScreen.self, action: #selector(HomeScreen.tapSettings(_:)), forControlEvents: UIControlEvents.TouchUpInside)
我希望这会有所帮助
答案 1 :(得分:0)
您的代码中存在两个问题:
当您将按钮的目标设置为HomeScreen的实例时,您将该按钮的目标设置为self
,如果这是您要调用的方法的声明
按钮操作方法收到的参数不是UITapGestureRecognizer
,而是点击了按钮,因此您应该用以下内容替换tapSettings
方法:
func tapSettings(button: UIButton){