繁体   English   中英

addTarget()在自定义扩展名上不起作用

[英]addTarget() does not work on custom extensions

我做了一个自定义的UIView() ,我试图向它添加一个okButton。

然而。 我已经添加了按钮,但是当在我的一个ViewController中显示UIView时,该按钮将不起作用。 这是我的代码:

class Luna: UIView {

let luna = UIView()
let okButton = UIButton()
typealias completionHandler = (_ success:Bool) -> Void


// Not yet implemented
open var touchOutsideToHide: Bool = true;

private var screenWidth: CGFloat {
    return UIScreen.main.bounds.width
}


override init(frame: CGRect) {
    super.init(frame: frame)
    okButton.setTitleColor(.blue, for: .normal)
    okButton.setTitle("Okay", for: .normal)
    okButton.titleLabel?.font = UIFont(name: "avenirnext-demibold", size: 16)

    let gesture:UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(self.pressButton(_:)))
    okButton.addGestureRecognizer(gesture)
}

required public init?(coder aDecoder: NSCoder) {
    super.init(coder: aDecoder)

}

}

 //The target function
@objc func pressButton(_ sender: UIButton){ //<- needs `@objc`
    // .. //
    print("btn hit")
}

我没有在控制台中btn hit ,并且水龙头未注册

该按钮可见,将其添加为子视图: 屏幕快照

按钮具有默认的触摸手势,您无需添加它。 只需按照以下步骤添加目标即可解决问题。 创建您的客户类别的协议,并在以下相同的类别中为其声明委托。

protocol LunaDelegate: class {
    func okButtonTapped(sender: UIButton)
}

class Luna: UIView {

    let luna = UIView()
    let okButton = UIButton()
    typealias completionHandler = (_ success:Bool) -> Void

    weak var delegate: LunaDelegate?

    // Not yet implemented
    open var touchOutsideToHide: Bool = true;

    private var screenWidth: CGFloat {
        return UIScreen.main.bounds.width
    }


    override init(frame: CGRect) {
        super.init(frame: frame)
        okButton.setTitleColor(.blue, for: .normal)
        okButton.setTitle("Okay", for: .normal)
        okButton.titleLabel?.font = UIFont(name: "avenirnext-demibold", size: 16)
        okButton.addTarget(self, action: #selector(pressButton(sender:)), for: .touchUpInside)
}

@IBAction func pressButton(sender: UIButton) {
    if let selfDelegate = self.delegate {
        selfDelegate.okButtonTapped(sender: sender)
    }
}

required public init?(coder aDecoder: NSCoder) {
    super.init(coder: aDecoder)
    }
}

然后,按照以下说明实现您的代码以使用自定义视图。 当按下按钮时,将在视图控制器中调用委托方法。

用法:

class LunaViewController: UIViewController, LunaDelegate {

    override func viewDidLoad() {
        super.viewDidLoad()

        let luna = Luna(frame: CGRect.init(x: 100, y: 100, width: 100, height: 40))
        luna.delegate = self
        self.view.addSubview(luna)
    }

    // MARK:- Luna Delegate
    func okButtonTapped(sender: UIButton) {
        print("OK Button Pressed From Luna View")
    }
}

这是我在当前项目中已经使用的正确解决方案。 我希望这能帮到您。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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