【问题标题】:UITextfield Class to call delegate methods in swiftUITextfield 类快速调用委托方法
【发布时间】:2018-11-12 07:20:15
【问题描述】:

我已经根据我的应用程序 UI 创建了一个自定义 UITextfield 类。但是我希望将一些委托方法包含在类中,因此我不需要在所有类中都编写它们。

open class SAIconTextField: SkyFloatingLabelTextFieldWithIcon {

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

/// Override init method
override init(frame: CGRect) {
    super.init(frame: frame)
    configure()
}

/// Override layoutSubviews method
override open func layoutSubviews() {
    super.layoutSubviews()
}

///  This method is used to set general UI
func configure() {
    self.tintColor = UIColor.appBlue
    self.selectedTitleColor = .appBlue
    self.selectedLineColor = .appBlue
    self.selectedLineHeight = 0.5

    self.iconColor = .lightGray
    self.iconImageView.tintColor = .lightGray
    self.selectedIconColor = .appBlue
    self.iconMarginBottom = 7.0
    //        self.iconMarginLeft = 2.0
    self.errorColor = .errorColor
}
}

我已经扩展了我的类以执行委托方法,以便所有文本字段都阻止在我的应用程序中输入表情符号,但没有调用该方法。

// MARK: - UITextFieldDelegate
extension SAIconTextField: UITextFieldDelegate {

/// Delegate method
public func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
    if textField.textInputMode?.primaryLanguage == "emoji" || !((textField.textInputMode?.primaryLanguage) != nil) {
        return false
    }
    return true
}
}

还有其他方法可以做类似的事情吗?

【问题讨论】:

    标签: swift uitextfielddelegate


    【解决方案1】:

    您没有设置文本字段委托。

    将此行添加到您的 configure() 函数中:

    delegate = self
    

    【讨论】:

    • 在课堂上添加委托=自我;调用类委托方法,但避免调用对于所有类都不相似的视图控制器的委托方法。因此可以调用任何类委托方法或 ViewController 的。是否有任何逃生窗口,以便我可以从它们中调用委托方法?
    • 正如 Stas Baranovskiy 所写,您不能同时设置两个不同的委托对象
    【解决方案2】:

    根据您共享的代码,我可以说 UITextFieldDelegate 的函数 textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool 未被调用,因为未设置委托对象。

    【讨论】:

    • 另外你不能同时设置两个不同的委托对象。 IE。为您设置自定义文本字段类仅处理一个委托函数,您的视图控制器处理其余部分。为此,您必须“代理”委托回调。我还建议您阅读以下主题 - stackoverflow.com/questions/32542362/…
    猜你喜欢
    • 1970-01-01
    • 2012-09-26
    • 2011-10-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-12
    • 2016-09-28
    • 1970-01-01
    相关资源
    最近更新 更多