我的设置很简单:
- 我有一个
UITextField
(输入视图是一个选择器视图) - 我有
UITextView
- 我有
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
方法中。两者都没有任何区别。
该按钮始终保持启用状态。请帮忙!谢谢,如果您需要我的更多信息,请告诉我。
userInteractionEnabled
忽略所有用户事件,但不"启用/禁用"控件。这不是您需要设置才能执行此操作的内容。 您应该设置button.enabled
。启用设置实际上启用或禁用控件。
if subjectTextField.text!.isEmpty || bodyTextView.text.isEmpty {
button.enabled = false
}else {
button.enabled = true
}
我不会在 viewDidLoad 中执行此操作,因为它只会在视图最初加载时运行 - 而是使用 textviewDelegate 方法。
你应该改变两件事。
-
使用
button.enabled
而不是button.userInteractionEnabled
。 尽管它们都实现了相同的目的,但如果您设置enabled
状态,用户将能够看到正在发生的事情。 -
每次两个字段中的文本更改时,您都需要不断检查
button
的状态。 您可以将textViewDidChange
用于文本视图,前提是您已将UITextViewDelegate
添加到类中,并且可以设置自己的TextFieldDidChange
函数并链接文本字段的Editing Changed
事件