简体   繁体   中英

Swift Variable used within its own initial value while using #selector

I'm trying to invoke my method from selector (action) but getting error Variable used within its own initial value Below is my code snippet

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

Below is the method which I'm calling

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

My method accepts 2 paramters. I don't know how to call it. The way I'm currently calling the sendRequestMethod is throwing error. Please help me to get it resolved.

when those functions are inside an UIView, as GestureRecognizers usually are, then you can make a hittest and find what UIView was under your touch.
Consider this is not the ideal way to catch touched views. As every UIView also offers you a .tag you can set a numbering and use it to make assumtions to whom the hit UIView fits. See Example

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)
        }
    }
}

Hint: Much easier is to subclass UIView and prepare a property that holds UserID given when allocation is done. addtarget: action:#selector() to each of them. The action/selector method gets invoked and the sender is passed in and because you know the type of the sender (YourUserUIView) you find the UserID.

With GestureRecognizer's you tend to write recognition code that can become very complex the more complex your UI will be, instead of just passing objects to actions that tell you what you are looking for.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM