ios - 如何使用自动布局在 subview 中创建 UIGestureRecognizer?

标签 ios swift autolayout uigesturerecognizer

当我尝试在 subview 中使用 UIGestureRecognizer 时,其框架是通过 superviewcontroller 中的自动布局指定的,它不会响应手势。我相信这是因为手势识别器不知道 View 的真实尺寸,正如自动布局约束所描述的那样。这怎么能解决?这是我的代码:

import UIKit
class MyLabel: UILabel {
    var delegate: MyProtocolForSwipeRecognition!
    var gestureRecognizer: UISwipeGestureRecognizer
    init() {
        gestureRecognizer = UISwipeGestureRecognizer(target: delegate, action: "swiped")
        super.init(frame: CGRect()) //<- I believe my problem is because it thinks
        //the frame is this empty CGRect, but I don't know what else to put here.
        translatesAutoresizingMaskIntoConstraints = false
        addGestureRecognizer(gestureRecognizer)
    }
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

提前致谢。

最佳答案

您的方法有两个问题(自动布局不是问题):

  1. 您必须在您的 MyLabel 类上设置 userInteractionEnabled = true
  2. 添加手势识别器时,必须确保 delegate 不为 nil。您可以通过添加一个将委托(delegate)作为参数的初始化程序来做到这一点

这是让它工作的方法(无需保留对手势识别器的引用):

class MyLabel: UILabel {
    var delegate: MyProtocolForSwipeRecognition

    init(withDelegate delegate: MyProtocolForSwipeRecognition) {
        self.delegate = delegate
        let gestureRecognizer = UISwipeGestureRecognizer(target: delegate, action: "swiped")
        super.init(frame: CGRectZero)
        addGestureRecognizer(gestureRecognizer)
        userInteractionEnabled = true
    }
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

然后你可以在实现你的协议(protocol)的类中初始化你的标签:

let label = MyLabel(withDelegate: self)

关于ios - 如何使用自动布局在 subview 中创建 UIGestureRecognizer?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34443020/

相关文章:

ios - Objective-C 中的 "accessors"是什么?

objective-c - 在 iPad 绘画应用程序中设置颜色

ios - swift ,Alamofire,SwiftyJSON : How to parsing arrayObject

ios - 以编程方式使用 Autolayout 添加 UISLider

iOS 自动布局坐标和以编程方式绘制 View

ios - 在 JSON 中,我在 "title"中获取以下格式的数据,如何获取实际数据?

ios - 将 collectionviewcell 大小设置为等于内容

swift - 在 macOS 上使用 Swift 3 从剪贴板读取

core-data - 在 CoreData 中保存 Swift CLLocation

swift - 更改堆栈 View 中多个字段之一的高度