[英]Swift: programmatically add UITapGestureRecognizer doesn't work
I have this code block, but it does not work the way I want to.我有这个代码块,但它不像我想要的那样工作。 datum_view appear good, but to no avail I click on it, it does not work.
datum_view 看起来不错,但我点击它无济于事,它不起作用。
Update code:更新代码:
var containerView: UIView!
var tov_datum = [String]()
var datum_view: UIView!
override func viewDidLoad() {
super.viewDidLoad()
containerView = UIView()
let SCREEN_SIZE = UIScreen.mainScreen().bounds
var Y: CGFloat = 0
for index in tov_datum {
datum_view = UIView(frame: CGRectMake(0, Y, SCREEN_SIZE.width, 80))
let gradientView = GradientView(frame: datum_view.bounds)
datum_view.insertSubview(gradientView, atIndex: 0)
let tapGestureRecognizer = UITapGestureRecognizer(target:self, action:"klikk:")
datum_view.userInteractionEnabled = true
datum_view.addGestureRecognizer(tapGestureRecognizer)
containerView.addSubview(datum_view)
Y = Y + 80
}
let YY = tov_datum.count * 80
NSLayoutConstraint(item: vetítésekView, attribute: .Height, relatedBy: .Equal, toItem: nil, attribute:.NotAnAttribute, multiplier: 1.0, constant:CGFloat(YY)).active = true
vetítésekView.addSubview(containerView)
}
func klikk(recognizer: UITapGestureRecognizer) {
print("BOOOOYAAAA")
}
Doesn't look like the size of containerView
is set anywhere.看起来没有在任何地方设置
containerView
的大小。 To quickly see if that's the problem, initialize it with the frame you're creating datum_view
inside:要快速查看这是否是问题所在,请使用您在其中创建
datum_view
的框架对其进行初始化:
let SCREEN_SIZE = UIScreen.mainScreen().bounds
containerView = UIView(frame: SCREEN_SIZE)
If that works, then figure out what size you actually want containerView to be and set up appropriate constraints.如果可行,那么确定您实际希望 containerView 的大小并设置适当的约束。
Change改变
func klikk(recognizer: UITapGestureRecognizer)
to到
func klikk(_ recognizer: UITapGestureRecognizer)
Change this line :改变这一行:
let tapGestureRecognizer = UITapGestureRecognizer(target:self, action:Selector("klikk:"))
to :到 :
let tapGestureRecognizer = UITapGestureRecognizer(target:self, action:"klikk:")
您应该将 tapGestureRecognizer 声明为属性。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.