【问题标题】:Swift Variable used within its own initial value while using #selector使用#selector时在其自己的初始值中使用的Swift变量
【发布时间】:2020-11-16 01:41:06
【问题描述】:

我正在尝试从选择器(操作)调用我的方法,但收到错误变量在其自己的初始值中使用下面是我的代码 sn-p

let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(sendRequest(tapGestureRecognizer, userID)))

下面是我调用的方法

@objc func sendRequest(tapGestureRecognizer: UITapGestureRecognizer, identifer: String) {
   print("hello world")
}

我的方法接受 2 个参数。我不知道怎么称呼它。我当前调用 sendRequestMethod 的方式是抛出错误。 请帮我解决。

【问题讨论】:

  • 请参阅developer.apple.com/documentation/uikit/uigesturerecognizer 并注意“调用的操作方法必须符合以下签名之一:”部分。
  • @PhillipMills 如果我修改我的 sendRequest 方法并删除第二个参数并将其称为 #selector(sendRequest(tapGestureRecognizer:) 那么它工作正常。我需要有关如何调用具有 2 个参数的方法的帮助。
  • 文档说只允许 0 或 1。也许你可以继承 UITapGestureRecognizer 并在那里添加一个 identifier 属性。

标签: ios objective-c swift xcode swift5


【解决方案1】:

当这些功能在 UIView 中时,就像 GestureRecognizers 通常那样,那么您可以进行最热门的测试并找到您所触摸的 UIView。
考虑到这不是捕捉触摸视图的理想方式。由于每个 UIView 还为您提供了一个 .tag,您可以设置一个编号并使用它来假设命中的 UIView 适合谁。查看示例

class checkCheckView : UIView {
        
    override init(frame: CGRect) {
        super.init(frame: frame)
    }
    
    required init?(coder: NSCoder) {
        super.init(coder: coder)
    }
    
    let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(sendRequest(recognizer:identifer:)) )

    @objc func sendRequest(recognizer:UITapGestureRecognizer, identifer:String) {
        print("hello world")
        // your problem will be, how is identifier passed in here?
    }

    let PanGestureRecognizer = UIPanGestureRecognizer(target: self, action: #selector(panning(gesture:)))
    
    @objc func panning(gesture:UIPanGestureRecognizer) {
        //print("pan-translation %@", gesture.translation(in: self).debugDescription)
        let location = gesture.location(ofTouch: 0, in: self)
        //print("pan-location %@",location.debugDescription);
        let hitview = self.hitTest(location, with: nil)
        if hitview != nil {
            let UserIDTag = hitview?.tag ?? 0
            print("userId by UIView tag",UserIDTag)
        }
    }
}

提示:继承 UIView 并准备一个属性来保存分配完成时给定的 UserID 更容易。 addtarget: action:#selector() 给他们每个人。调用操作/选择器方法并传入发送者,因为您知道发送者的类型 (YourUserUIView),所以您可以找到用户 ID。

使用 GestureRecognizer,您倾向于编写识别代码,如果您的 UI 越复杂,识别代码就会变得越复杂,而不仅仅是将对象传递给告诉您正在查找的内容的操作。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-04-19
    • 1970-01-01
    • 1970-01-01
    • 2021-06-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多