在标签上添加手势?

时间:2018-09-25 08:58:27

标签: ios swift uilabel uigesturerecognizer unrecognized-selector

Swift 4 iOS 11

尝试使用此代码向标签添加手势,它会触发但不会因选择器无法识别而崩溃。

尝试使用和不使用@objc,也尝试使用@selector(ViewController.copyURL),尝试打开isUserInteractiveEnabled = true;没有用

@IBOutlet weak var zeroURL: UILabel!

let press = UILongPressGestureRecognizer(target: zeroURL, action: #selector(copyURL))
view.addGestureRecognizer(press)

@objc func copyURL() {
    UIPasteboard.general.string = self.zeroURL.text
    print("copied")
    zeroURL.alpha = 0
    UIView.animate(withDuration: 0.75, delay: 0.25, options: [.curveEaseOut], animations: {
        self.zeroURL.alpha = 1.0
    }) { (status) in
        // do nothing
    }
}

3 个答案:

答案 0 :(得分:3)

目标应该是自我,您需要将手势识别器添加到标签,而不是视图

let press = UILongPressGestureRecognizer(target: self, action: #selector(copyURL))
zeroURL.addGestureRecognizer(press)

在这里的第一行上,您正在配置手势识别器,告诉它self.copyURL是识别该手势时要使用的目标操作。第二行将手势添加到UILabel

答案 1 :(得分:1)

替换此

let press = UILongPressGestureRecognizer(target: zeroURL, action: #selector(copyURL))
view.addGestureRecognizer(press)

使用

let press = UILongPressGestureRecognizer(target: self, action: #selector(copyURL))
zeroURL.addGestureRecognizer(press)

作为目标应包含选择器方法的实现

答案 2 :(得分:1)

使目标self而不是zeroURL如下:

let press = UILongPressGestureRecognizer(target: self, action:#selector(copyURL))
zeroURL.addGestureRecognizer(press)

@objc func copyURL() {
    UIPasteboard.general.string = self.zeroURL.text
    print("copied")
    zeroURL.alpha = 0
    UIView.animate(withDuration: 0.75, delay: 0.25, options: [.curveEaseOut], animations: {
    self.zeroURL.alpha = 1.0
    }) { (status) in
        // do nothing
    }
}

编辑:仅在UILabel上添加长按手势,而不是在view上添加长按手势,如下所示:

zeroURL.addGestureRecognizer(press)