Iphone 编辑完成后如何检查UITextField文本是否为空

Iphone 编辑完成后如何检查UITextField文本是否为空,iphone,objective-c,ios,cocoa-touch,uitextfield,Iphone,Objective C,Ios,Cocoa Touch,Uitextfield,我当前有一个带有默认文本的UITextField,并在编辑开始时设置为clear。我试图这样做,如果编辑完成时字段为空或为零,文本值将再次成为默认文本。我在检测编辑完成或键盘关闭时遇到问题。谁能告诉我我想使用哪种检测方法以及如何实现它?非常感谢 编辑 占位符不能用于我的情况我认为您不需要自己处理“默认文本”。检查类的占位符属性 更新 因此,占位符不适合您的情况。您是否尝试为您的UITextField实现方法并更改textviewdendediting:中的文本 为此,请在视图控制器中实现那些

我当前有一个带有默认文本的UITextField,并在编辑开始时设置为clear。我试图这样做,如果编辑完成时字段为空或为零,文本值将再次成为默认文本。我在检测编辑完成或键盘关闭时遇到问题。谁能告诉我我想使用哪种检测方法以及如何实现它?非常感谢


编辑

占位符
不能用于我的情况

我认为您不需要自己处理“默认文本”。检查类的
占位符
属性

更新

因此,
占位符
不适合您的情况。您是否尝试为您的
UITextField
实现方法并更改
textviewdendediting:
中的文本

为此,请在视图控制器中实现那些看起来对您的场景有用的
UITextFieldDelegate
方法,并将
UITextField
delegate
设置到视图控制器(通过界面生成器或编程方式)。在
textViewDiEndediting:
方法中设置默认文本


您可以参考。

的“获取输入的文本并设置文本”部分。当您获得文本字段返回时的代理调用时,使用
发送者
参数检查文本(
发送者.Text
),如果它等于
@”“
设置您的默认文本。

您必须使用textfield委托

-(void)textFieldDidEndEditing:(UITextField *)textField;
在这个委托中,像这样进行检查

if ( [textField.text length] == 0 )
{
    // the text field is empty do your work
} else {
    ///  the text field 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
}

我使用两种方法。我的选择取决于应用程序业务逻辑

1) 我在应用
shouldChangeCharacters中的更改后检查结果文本

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
    }

是的,我实际上需要有默认文本,因为它的值是在编辑后立即使用的,我不能只使用占位符。我试过了,但我们的客户不希望:)添加了一个指向有关管理文本字段的官方文档的链接。如果用户突出显示从0索引开始的文本子集,然后将其删除,这将不起作用。@Alexiscandellia,我又发布了一个答案
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
    }
@IBAction private func textFieldDidChange(_ sender: UITextField) {
        if (sender.text?.count ?? 0) == 0 {
            // textField is empty
        } else {
            // textField is not empty
        }
    }