iOS:在Swift中重新创建addTarget()的最佳实践?

时间:2018-01-18 18:55:22

标签: ios swift uicontrol

我正在创建一个自定义UIControl子类,并希望添加一个addTarget()函数,类似于UIButton。我该怎么做呢?到目前为止,我有这个(它有效,但不确定是否是一个很好的解决方案):

import UIKit

class RichLabel: UIControl {

    var labelTarget: Any?
    var labelAction: Selector?

    override init(frame: CGRect) {
        super.init(frame: frame)
    }

    required init?(coder _: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    func addTarget(_ target: Any?, action: Selector) {
        self.labelTarget = target
        self.labelAction = action
    }

    func buttonAction() {

        if let labelTarget = labelTarget, let labelAction = labelAction {               
         let _ = (labelTarget as AnyObject).perform(labelAction, with: self)
    }
}

目标是从另一个视图添加的,如下所示:

var richLabel: RichLabel {
    let label = RichLabel()
    label.setAttributedText(title: string)
    label.addTarget(self, action: #selector(richLabelAction(label:)))
    return label
}

2 个答案:

答案 0 :(得分:3)

如果您继承自UIControl,则无需对addTarget执行任何操作。呼叫者将在您的自定义UIControl上使用addTarget,就像使用任何其他控件一样。您的自定义控件所要做的就是决定何时调用这些操作,然后调用sendActions(for:)

如果您的目标是让这个RichLabel类功能就像一个按钮,我会向其添加UITapGestureRecognizer,并在手势识别器中调用self.sendActions(for: .touchUpInside)

class RichLabel: UIControl {

    override init(frame: CGRect) {
        super.init(frame: frame)
        let tapGesture = UITapGestureRecognizer(target: self, action: #selector(labelTapped))
        addGestureRecognizer(tapGesture)
    }

    required init?(coder _: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    @objc func labelTapped() {
        // When this happens, any object that called `addTarget`
        // for the .touchUpInside event will get its callback triggered
        sendActions(for: .touchUpInside)
    }

}

答案 1 :(得分:1)

由于while read -r line || [ -n "$line" ]; do curl -o "${line#*,}" "http://example.com/${line%,*}/default.jpg" done < file.csv 已经允许您访问UIControl,因此您可以使用它。例如,如果您将标签添加到func addTarget(_ target: Any?, action: Selector, for controlEvents: UIControlEvents),并希望viewController能够对UIViewController之类的内容作出反应,则可以将此代码添加到viewController:

editingDidBegin

我不确定您的@IBOutletWeak var richLabel: RichLabel! override func viewDidLoad() { super.viewDidLoad() self.richLabel.addTarget(self, action: #selector(labelEditingDidBegin(_:)), for: UIControlEvents.editingDidBegin) } @objc func labelEditingDidBegin(_ sender: RichLabel) { print(sender.text) } 是否允许编辑等,但您可以观察您需要的RichLabel,对此做出反应,然后执行您{{{}所需的任何代码1}}功能。