如何扩展UIView以方便使用tapGestureRecognizer?

问题描述 投票:0回答:1

这是 UIView 的扩展,可以轻松地将

UITapGestureRecognizer
添加到
UIImageView
:

extension UIView {

    fileprivate struct AssociatedObjectKeys {
        static var tapGestureRecognizer = "MediaViewerAssociatedObjectKey_mediaViewer"
    }

    fileprivate typealias Action = (() -> Void)?

    fileprivate var tapGestureRecognizerAction: Action? {
        set {
            if let newValue = newValue {
                // Computed properties get stored as associated objects
                objc_setAssociatedObject(self, &AssociatedObjectKeys.tapGestureRecognizer, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN) //Forming 'UnsafeRawPointer' to an inout variable of type String exposes the internal representation rather than the string contents.
            }
        }
        get {
            let tapGestureRecognizerActionInstance = objc_getAssociatedObject(self, &AssociatedObjectKeys.tapGestureRecognizer) as? Action //Forming 'UnsafeRawPointer' to an inout variable of type String exposes the internal representation rather than the string contents.
            return tapGestureRecognizerActionInstance
        }
    }

    public func addTapGestureRecognizer(action: (() -> Void)?) {
        self.isUserInteractionEnabled = true
        self.tapGestureRecognizerAction = action
        let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(handleTapGesture))
        self.addGestureRecognizer(tapGestureRecognizer)
    }

    @objc fileprivate func handleTapGesture(sender: UITapGestureRecognizer) {
        if let action = self.tapGestureRecognizerAction {
            action?()
        } else {
            print("no action")
        }
    }
}

但是 xcode 两次告诉我 set 和 get 方法:>将“UnsafeRawPointer”形成为 String 类型的 inout 变量会公开内部表示而不是字符串内容。

我需要做什么才能使其静音? 我注意到代码可以工作,但有两个警告。 谢谢你

swift uiview uitapgesturerecognizer
1个回答
0
投票

警告警告您

&AssociatedObjectKeys.tapGestureRecognizer
不会评估为指向包含字符串字符的缓冲区的指针(正如某些人所期望的那样)。相反,它指向字符串的“内部表示”。

另请参阅这篇文章,了解当您尝试使用

&
获取其他非平凡类型的原始指针时发出的措辞略有不同的警告。您收到的警告是一种特殊版本,专门针对字符串。

当然,在这种情况下你不想获取字符串的内容。您只需要一个固定地址作为关联对象的键,因此该警告是误报。消除警告的最简单方法是使用简单类型(请参阅here了解“trivial”的含义),例如

Int

static var tapGestureRecognizer = 0

关联对象的键不需要是指向字符串的指针。

© www.soinside.com 2019 - 2024. All rights reserved.