当UITextField中有文本时,如何删除子视图?

时间:2017-04-29 03:06:43

标签: ios swift uitextfield

到目前为止,这是我尝试实现这一目标。

    if searchBar.text == ""
    {
        searchBar.addSubview(placeholder)

        searchBar.addConstraintsWithFormat("V:|[v0]|", views: placeholder)

        phconstraint = NSLayoutConstraint(item: placeholder, attribute: .centerX, relatedBy: .equal, toItem: searchBar, attribute: .centerX, multiplier: 1, constant: 0)
    }
    else
    {
        placeholder.removeFromSuperview()
    }

以上代码最能说明我想要实现的逻辑。 UITextField中是否有一些方法可以检测文本的添加或是否有一些通知?

有什么建议吗?

1 个答案:

答案 0 :(得分:0)

这是您应该编写逻辑来隐藏/显示视图的方法:

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        let currentString: String = (textField.text! as NSString).replacingCharacters(in: range, with: string)
        let length: Int = (currentString.characters.count )

        if(length >= 1){
        //show
        }
        else{
        //hide
        }
       return true
    }