【问题标题】:Disable UIButton if UITextField and UITextView are empty in Swift如果 UITextField 和 UITextView 在 Swift 中为空,则禁用 UIButton
【发布时间】:2016-06-10 02:15:51
【问题描述】:

我的设置很简单:

  1. 我有一个UITextField(输入视图是一个pickerView)
  2. 我有一个UITextView
  3. 我有一个UIButton

如果 文本字段和文本视图都为空,我只想禁用该按钮。并在它们都包含某些内容时启用它。

我尝试的任何方法似乎都不起作用。

我用这个创建我的按钮:

    let button   = UIButton(type: UIButtonType.System) as UIButton
    button.frame = CGRectMake(self.view.frame.width, self.view.frame.height - 90, self.view.frame.width - 60, 50)
    button.center.x = self.view.frame.width / 2
    button.backgroundColor = UIColor.clearColor()
    button.layer.cornerRadius = 25
    button.layer.borderWidth = 1
    button.layer.borderColor = UIColor(hue: 359/360, saturation: 67/100, brightness: 71/100, alpha: 1).CGColor
    button.tintColor = UIColor(hue: 359/360, saturation: 67/100, brightness: 71/100, alpha: 1)
    button.setTitle("Send email", forState: UIControlState.Normal)
    button.titleLabel!.font =  UIFont(name: "Typo GeoSlab Regular Demo", size: 15)
    button.addTarget(self, action: "sendEmail:", forControlEvents: UIControlEvents.TouchUpInside)
    self.view.addSubview(button)

对于文本字段的检查,我已经尝试过:

    if subjectTextField.text!.isEmpty || bodyTextView.text.isEmpty {

        button.userInteractionEnabled = false

    } else {

        button.userInteractionEnabled = true
    }

我也试过这个:

    if subjectTextField.text == "" || bodyTextView.text == "" {

        button.userInteractionEnabled = false

    } else {

        button.userInteractionEnabled = true
    }

我已经在viewDidLoad() 方法中添加了这段代码,也尝试在textFieldDidEndEditing 方法中添加它。两者都没有任何区别。

始终按钮保持启用状态。请帮忙! 谢谢,如果您需要我提供更多信息,请告诉我。

【问题讨论】:

  • 尝试检查文本字段和文本视图中的文本长度... subjectTextField.text.length==0 || bodyTextView.text.length==0

标签: ios swift uibutton uitextfield uitextview


【解决方案1】:

userInteractionEnabled 忽略所有用户事件,但不“启用/禁用”控件。这不是您需要设置的内容。你应该设置button.enabled。 Enabled 设置实际上是启用或禁用控件。

  if subjectTextField.text!.isEmpty || bodyTextView.text.isEmpty {
       button.enabled = false
  }else {
       button.enabled = true
  }

我不会在 viewDidLoad 中执行此操作,因为它只会在视图最初加载时运行 - 而是 textviewDelegate 方法。

【讨论】:

  • 你能建议把这段代码放在哪里最好吗?看到一个是 UITextfield,另一个是 UITextView...?
【解决方案2】:

你应该改变两件事。

  1. 使用button.enabled 而不是button.userInteractionEnabled。尽管它们都达到了相同的目的,但如果您设置enabled 状态,用户将能够看到发生了什么

  2. 每次您的两个字段中的文本发生变化时,您都需要不断检查button 的状态。你可以在文本视图中使用textViewDidChange,前提是你已经在类中添加了UITextViewDelegate,并且你可以设置自己的TextFieldDidChange函数并为文本字段链接Editing Changed事件

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-01-09
    • 2017-04-05
    • 1970-01-01
    • 2020-06-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多