我正在尝试在动态创建的标签上添加手势,但它没有使用此代码,但它不起作用。 我做错了什么?
let label = UILabel(frame: CGRect(x: 0, y: 0, width: 200, height: 21))
label.center = CGPoint(x: 160, y: 285)
label.textAlignment = .center
label.text = field.text
label.isZoomEnabled = true;
label.minFontSize = 10;
label.maxFontSize = 80;
label.adjustsFontSizeToFitWidth = true;
label.setNeedsLayout()
label.isUserInteractionEnabled = true
let panRecognizer = UITapGestureRecognizer(target: self, action:Selector(("handlePan:")))
let rotateRecognizer = UITapGestureRecognizer(target: self, action:Selector(("handleRotate:")))
panRecognizer.delegate = self
rotateRecognizer.delegate = self
label.addGestureRecognizer(panRecognizer)
label.addGestureRecognizer(rotateRecognizer)
self.view.addSubview(label);
self.imagePicked.addSubview(label)
@IBAction func handlePan(recognizer:UIPanGestureRecognizer) {
let translation = recognizer.translation(in: self.view)
if let view = recognizer.view {
view.center = CGPoint(x:view.center.x + translation.x,
y:view.center.y + translation.y)
}
recognizer.setTranslation(CGPoint(x:0,y:0), in: self.view)
}
@IBAction func handleRotate(recognizer : UIRotationGestureRecognizer) {
if let view = recognizer.view {
view.transform = view.transform.rotated(by: recognizer.rotation)
recognizer.rotation = 0
}
}
提前致谢。
答案 0 :(得分:0)
这是UIlabel's
superView的问题。
我认为imagePicked
是UIImageView
的实例,默认值为UIImageView's
isUserInteractionEnabled
。
因此imagePicked
及其所有子视图无法接收触摸事件。
要解决此问题,请使用UIImageView的isUserInteractionEnabled
属性:
self.imagePicked.isUserInteractionEnabled = true;
答案 1 :(得分:0)
您正在创建UITapGestureRecognizer
,但这些方法正在使用UIPanGestureRecognizer
和UIRotationGestureRecognizer
。还更改了selector
,以便正确调用方法并将IBActions
更改为方法。
用这个替换你的代码,它会正常工作,
let label = UILabel(frame: CGRect(x: 0, y: 0, width: 200, height: 21))
label.center = CGPoint(x: 160, y: 285)
label.textAlignment = .center
label.text = field.text
label.isZoomEnabled = true;
label.minFontSize = 10;
label.maxFontSize = 80;
label.adjustsFontSizeToFitWidth = true;
label.setNeedsLayout()
label.isUserInteractionEnabled = true
let panRecognizer = UIPanGestureRecognizer(target: self, action:#selector(self.handlePan))
let rotateRecognizer = UIRotationGestureRecognizer(target: self, action:#selector(self.handleRotate))
panRecognizer.delegate = self
rotateRecognizer.delegate = self
label.addGestureRecognizer(panRecognizer)
label.addGestureRecognizer(rotateRecognizer)
self.view.addSubview(label);
self.imagePicked.addSubview(label)
func handlePan(recognizer:UIPanGestureRecognizer) {
let translation = recognizer.translation(in: self.view)
if let view = recognizer.view {
view.center = CGPoint(x:view.center.x + translation.x,
y:view.center.y + translation.y)
}
recognizer.setTranslation(CGPoint(x:0,y:0), in: self.view)
}
func handleRotate(recognizer : UIRotationGestureRecognizer) {
if let view = recognizer.view {
view.transform = view.transform.rotated(by: recognizer.rotation)
recognizer.rotation = 0
}
}