【问题标题】:If textfield is empty set border to red, if we enter text, remove red border如果 textfield 为空,则将边框设置为红色,如果我们输入文本,则删除红色边框
【发布时间】:2021-12-23 01:43:08
【问题描述】:

在 Swift 中,我为文本字段添加了红色边框。我想实现,如果我们在其中输入任何文本,则应删除文本字段边框颜色,如果其中再次没有文本,则应再次将边框颜色设置为红色。无需单击任何按钮。 (仅以编程方式)

【问题讨论】:

  • 你可以添加一个目标编辑Changed,并使用调用的方法做任何你需要的事情

标签: ios swift iphone ipad border


【解决方案1】:

这应该会有所帮助:

if self.yourTextField.text.isEmpty
{
   self.yourTextField.layer.borderColor = UIColor.red.cgColor
   self.yourTextField.layer.borderWidth = 1
}
else
{
   self.yourTextField.layer.borderWidth = 0
}

【讨论】:

  • 谢谢 :) 已更正。
【解决方案2】:

您可以使用以下简单代码来完成此操作。 在您的 viewdidload 或查看配置方法中添加以下行

textField.addTarget(self, action: #selector(ViewController.textFieldDidChange(_:)), for: .editingChanged)

根据需要更改文本字段边框颜色或删除边框

@objc func textFieldDidChange(_ textField: UITextField) {
        if (textField.text!.isEmpty)
        {
            // change your textfield border color
        }
        else
        {
            // remove text field border or change color
        }
    }

【讨论】:

  • 你可以简单地使用if textField.hasText {#selector(textFieldDidChange)
猜你喜欢
  • 2018-02-15
  • 2017-09-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-04-17
  • 2019-03-17
  • 2021-08-28
相关资源
最近更新 更多