簡體   English   中英

完成編輯后如何檢查 UITextField 文本是否為空

[英]How to check if UITextField text is empty when done editing

我目前有一個帶有默認文本的 UITextField,並在編輯開始時設置為清除。 我正在嘗試這樣做,以便在完成編輯時如果該字段為空或 nil,則文本值將再次成為默認文本。 我無法檢測何時完成編輯或關閉鍵盤。 誰能告訴我我想使用哪種檢測方法以及如何實現它? 非常感謝!


編輯


在我的情況下不能使用placeholder

您必須使用文本字段委托

-(void)textFieldDidEndEditing:(UITextField *)textField;

在這個委托中進行這樣的檢查

if ( [textField.text length] == 0 )
{
    // the text field is empty do your work
} else {
    ///  the text field is not empty 
}
- (BOOL)textField:(UITextField*)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString*)string
{
    if (range.location == 0 && string.length == 0)
    {
        //textField is empty
    }
    return YES;
}

我認為您不需要自己處理“默認文本”。 檢查UITextField類的placeholder屬性。

更新

所以placeholder不適合你的情況。 您是否嘗試為您的UITextField實現UITextFieldDelegate方法並更改textViewDidEndEditing:中的文本?

為此,請在視圖控制器中實現對您的場景有用的UITextFieldDelegate方法,並將UITextFielddelegate設置為視圖控制器(通過 Interface Builder 或以編程方式)。 textViewDidEndEditing:方法中設置默認文本。

您可以參考iOS 的文本、Web 和編輯編程指南的“獲取輸入的文本和設置文本”部分。

當您收到文本字段返回時的委托調用時,使用sender參數檢查文本( sender.text ),如果它等於@""則設置您的默認文本。

我使用兩種方法。 我的選擇取決於應用程序的業務邏輯。

1)我在shouldChangeCharactersIn應用更改后檢查結果文本:

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        var text = textField.text ?? ""

        let startIndex = text.index(text.startIndex, offsetBy: range.location)
        let endIndex = text.index(text.startIndex, offsetBy: range.location + range.length)
        text = text.replacingCharacters(in: startIndex..<endIndex, with: string)
        if text.count == 0 {
            // textField is empty
        } else {
            // textField is not empty
        }
        return true
    }

2)我使用editingChanged動作:

@IBAction private func textFieldDidChange(_ sender: UITextField) {
        if (sender.text?.count ?? 0) == 0 {
            // textField is empty
        } else {
            // textField is not empty
        }
    }

您還需要檢查刪除的范圍是否是文本的整個長度。

func textField(_ textField: UITextField, shouldChangeCharactersIn range:  NSRange, replacementString string: String) -> Bool {
    if !(range.location == 0 && string.count == 0 && range.length == textField.text?.count) {
      // Text field is empty
    }
    return true
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM