Swift 多文本字段参数

Posted

技术标签:

【中文标题】Swift 多文本字段参数【英文标题】:Swift Multiple Text Field Arguments 【发布时间】:2017-08-25 08:50:39 【问题描述】:

我有多个限制要添加到 2 个单独的文本字段中。

文本字段1 , textField2

两个文本字段

只允许一个小数

只允许长度为 8 个字符

"shouldChangeCharactersIn" - 如何使用此函数应用于多个文本字段并具有多个约束?

func textField(_ textField: UITextField,shouldChangeCharactersIn range: NSRange,replacementString string: String) -> Bool
    
    let countdots = (capitalInvested.text?.components(separatedBy: ".").count)! - 1

        if countdots > 0 && string == "."
        
            return false
        
        return true
        

【问题讨论】:

检查内部shouldChangeCharactersIn if (textField == textField1 || textField2) // apply your both conditions 【参考方案1】:

您需要检查正在输入的文本字段,它调用了该函数:

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool 
    if textField == textField1 
        // first text field
        // add restrictions here
     else if textField == textField2 
        // second text field
        // add restrictions here
    
    if textField == textField1 || textField == textField2 
        // restrictions for both
    

【讨论】:

以上是关于Swift 多文本字段参数的主要内容,如果未能解决你的问题,请参考以下文章