ios - 如果 UITextField 和 UITextView 在 Swift 中为空,则禁用 UIButton

标签 ios swift uibutton uitextfield uitextview

我的设置很简单:

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

我只想在文本字段和 TextView 两者为空时禁用该按钮。并在它们都包含某些内容时启用它。

我尝试的一切似乎都不起作用。

我用这个创建我的按钮:

    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。 Enabled 设置实际上启用或禁用控件。

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

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

关于ios - 如果 UITextField 和 UITextView 在 Swift 中为空,则禁用 UIButton,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35658930/

相关文章:

ios - 如何上传录制的音频文件进行解析?

ios - 如何删除 UICollectionView Flow 布局大小中的单元格空间?

swift - 如何在 UITableView 内的 UITabBar 顶部添加 UIButton

swift - 如何快速对 map 注释按钮执行操作

ios - 如何删除 YandexMapKit 中的分类地标?

ios - 禁用特定时间间隔的推送通知 iOS

ios - 在 Openshift 上使用 Node.js 发送 iOS 推送通知

ios - UIPageViewController 中的 UIImageView 大小调整问题

iphone - 无法让我的 UIButton 显示为半透明

ios - 图标角标(Badge)未出现在 IOS 10 模拟器中