Passing arguments to selector in Swift

后端 未结 6 700
闹比i
闹比i 2020-11-27 03:14

I\'m programmatically adding a UITapGestureRecognizer to one of my views:

let gesture = UITapGestureRecognizer(target: self, action: #selector(self.handleTap         


        
6条回答
  •  清歌不尽
    2020-11-27 03:28

    Just create a custom class of UITapGestureRecognizer =>

    import UIKit
    
    class OtherUserProfileTapGestureRecognizer: UITapGestureRecognizer {
    
        let userModel: OtherUserModel    
        init(target: AnyObject, action: Selector, userModel: OtherUserModel) {
            self.userModel = userModel
            super.init(target: target, action: action)
        }
    }
    

    And then create UIImageView extension =>

    import UIKit
    
        extension UIImageView {
        
            func gotoOtherUserProfile(otherUserModel: OtherUserModel) {
                isUserInteractionEnabled = true
                let gestureRecognizer = OtherUserProfileTapGestureRecognizer(target: self, action: #selector(self.didTapOtherUserImage(_:)), otherUserModel: otherUserModel)
                addGestureRecognizer(gestureRecognizer)
            }
            
            @objc internal func didTapOtherUserImage(_ recognizer: OtherUserProfileTapGestureRecognizer) {
                Router.shared.gotoOtherUserProfile(otherUserModel: recognizer.otherUserModel)
            }
        }
    

    Now use it like =>

    self.userImageView.gotoOtherUserProfile(otherUserModel: OtherUserModel)
    

提交回复
热议问题