Ios 如果Swift中的文本字段中未输入任何文本,则使UIButton处于非活动状态

Ios 如果Swift中的文本字段中未输入任何文本,则使UIButton处于非活动状态,ios,swift,uibutton,uitextfield,is-empty,Ios,Swift,Uibutton,Uitextfield,Is Empty,所以我的概念很简单,我有一个文本字段和一个标有“下一步”的按钮。如果用户没有在文本字段中添加任何内容,我希望禁用“下一步”按钮。为此,我运行了以下代码: @IBAction func nextButton(sender: UIButton) { if textField.text.isEmpty { buttonLabel.userInteractionEnabled = false } } 这会禁用我想要的按钮,但问题是,如果在文本字段中输入文本,按

所以我的概念很简单,我有一个文本字段和一个标有“下一步”的按钮。如果用户没有在文本字段中添加任何内容,我希望禁用“下一步”按钮。为此,我运行了以下代码:

 @IBAction func nextButton(sender: UIButton) {

    if textField.text.isEmpty {

        buttonLabel.userInteractionEnabled = false

    }
 }
这会禁用我想要的按钮,但问题是,如果在文本字段中输入文本,按钮仍然被禁用。我曾尝试在“if”语句之后添加“else”语句,以反转我所说的内容,看看它是否有效,但没有效果

非常感谢您的帮助

尼克

我的代码:

import UIKit

class ViewController: UIViewController, UITextFieldDelegate, UIPickerViewDataSource, UIPickerViewDelegate {

func imageEffect() {

    // Set vertical effect for background
    var verticalMotionEffect : UIInterpolatingMotionEffect =
    UIInterpolatingMotionEffect(keyPath: "center.y",
        type: .TiltAlongVerticalAxis)
    verticalMotionEffect.minimumRelativeValue = -20
    verticalMotionEffect.maximumRelativeValue = 20

    // Set horizontal effect for background
    var horizontalMotionEffect : UIInterpolatingMotionEffect =
    UIInterpolatingMotionEffect(keyPath: "center.x",
        type: .TiltAlongHorizontalAxis)
    horizontalMotionEffect.minimumRelativeValue = -20
    horizontalMotionEffect.maximumRelativeValue = 20

    // Create group for background to combine both
    var group : UIMotionEffectGroup = UIMotionEffectGroup()
    group.motionEffects = [horizontalMotionEffect, verticalMotionEffect]

    // Add both effects to your view for background
    myBackgroundView.addMotionEffect(group)

}

var datePickerView:UIDatePicker = UIDatePicker()

@IBAction func textFieldEdited(sender: UITextField) {

    var datePickerView  : UIDatePicker = UIDatePicker()
    datePickerView.datePickerMode = UIDatePickerMode.Date
    sender.inputView = datePickerView
    datePickerView.addTarget(self, action: Selector("handleDatePicker:"), forControlEvents: UIControlEvents.ValueChanged)

    }

func handleDatePicker(sender: UIDatePicker) {
    var dateFormatter = NSDateFormatter()
    dateFormatter.dateFormat = "dd MMMM yyyy"
    questionTextField.text = dateFormatter.stringFromDate(sender.date)
}

var countryData = ["United Kingdom", "France", "Spain", "Germany", "Berlin", "Eygpt", "United States"]

var pickerView:UIPickerView = UIPickerView()

@IBOutlet var progressStatus: UIProgressView!

@IBOutlet var barImage: UIImageView!

@IBOutlet var questionLabel: UILabel!

@IBOutlet var buttonBarImage: UIImageView!

@IBOutlet var buttonLabel: UIButton!

@IBOutlet var myBackgroundView: UIImageView!

@IBOutlet var questionTextField: UITextField!

let questions = ["Where are you going?", "What are you doing there?", "When do you go?"]

var currentQuestionIndex = 0

let placeholder = ["Country", "Activity", "Date"]

var currentPlaceholderIndex = 0

@IBAction func nextButton(sender: AnyObject) {

    if currentQuestionIndex == 0 {

        progressStatus.setProgress(0.333, animated: true)

    } else if currentQuestionIndex == 1 {

        progressStatus.setProgress(0.666, animated: true)

    } else {

        progressStatus.setProgress(1, animated: true)

    }

    // Initial setup on button press
    questionTextField.hidden = false
    barImage.hidden = false
    questionTextField.placeholder = placeholder[currentPlaceholderIndex]
    questionLabel.text = questions[currentQuestionIndex]
    questionTextField.resignFirstResponder()

    // Reset text field to have no text
    questionTextField.text = ""

    // Displays the questions in array and displays the placeholder text in the textfield
    if currentQuestionIndex <= questions.count && currentPlaceholderIndex <= placeholder.count {

        currentQuestionIndex++
        currentPlaceholderIndex++
        //progressStatus.setProgress(0.333, animated: true)
        buttonLabel.setTitle("Next", forState: UIControlState.Normal)


        // Animate text for questionLabel
        UIView.animateWithDuration(1.0, delay: 0.0, usingSpringWithDamping: 0.9, initialSpringVelocity: 0.5, options: nil, animations: {

            self.questionLabel.center = CGPoint(x: -110 , y: 305 + 20)

            }, completion: nil)

    } else {

        //Add some logic here to run whenever the user has answered all the questions.

    }

}


override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.

    questionTextField.delegate = self
    pickerView.delegate = self
    pickerView.dataSource = self

    // Applies the image effect to the image in myBackgroundImage
    imageEffect()

    // Sets the button text
    buttonLabel.setTitle("Get started", forState: UIControlState.Normal)

    // Sets the question text to be blank
    questionLabel.text = ""


    // Sets placeholder text in the text field
    questionTextField.placeholder = ""

    // Hides the text field
    questionTextField.hidden = true

    // Hides the image background for the text field
    barImage.hidden = true

    // Sets the progress bar to nil
    progressStatus.setProgress(0, animated: true)

    if questionTextField.text.isEmpty {

        buttonLabel.userInteractionEnabled = false
    }

}

func textFieldDidBeginEditing(textField: UITextField) {


    buttonLabel.userInteractionEnabled = true


    switch currentQuestionIndex {

    case 0:
        // TODO: Add UIPickerView
        self.view.addSubview(datePickerView)
    case 2:
        // TODO: Add UIDatePicker
        self.view.addSubview(datePickerView)

    default:
        println("default")
    }
}


// resigns the keyboard when user presses the return/next key on keyboard

func textFieldShouldReturn(textField: UITextField) -> Bool {

    questionTextField.resignFirstResponder()

    return true

}

func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int {

    return 1
}

func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {

    return countryData.count

}

func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String! {
    return countryData[row]

}

func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {

    questionTextField.text = countryData[row]
    pickerView.hidden = true

}




// Resigns the keyboard if the user presses anywhere on the screen
override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) {

    self.view.endEditing(true)
}


override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

}
导入UIKit
类ViewController:UIViewController、UIExtFieldDelegate、UIPickerViewData源、UIPickerViewDeleteGate{
func imageEffect(){
//设置背景的垂直效果
变量垂直运动效应:UIInterpolingMotionEffect=
UIInterpolingMotionEffect(关键路径:“center.y”,
类型:。倾斜方向(垂直轴)
verticalMotionEffect.minimumRelativeValue=-20
垂直运动效应最大相对值=20
//设置背景的水平效果
var水平运动效果:UIInterpolingMotionEffect=
UIInterpolingMotionEffect(关键路径:“center.x”,
类型:。沿水平轴倾斜)
horizontalMotionEffect.minimumRelativeValue=-20
horizontalMotionEffect.maximumRelativeValue=20
//为背景创建组以将两者结合起来
变量组:UIMotionEffectGroup=UIMotionEffectGroup()
group.motionEffects=[水平运动效果,垂直运动效果]
//将这两种效果添加到背景视图中
myBackgroundView.addMotionEffect(组)
}
var datePickerView:UIDatePicker=UIDatePicker()
@iAction func TextFieldEdit(发件人:UITextField){
var datePickerView:UIDatePicker=UIDatePicker()
datePickerView.datePickerMode=UIDatePickerMode.Date
sender.inputView=datePickerView
datePickerView.addTarget(自身,操作:选择器(“handleDatePicker:”),forControlEvents:UIControlEvents.ValueChanged)
}
func handleDatePicker(发送方:UIDatePicker){
var dateFormatter=NSDateFormatter()
dateFormatter.dateFormat=“dd-MMMM-yyyy”
questionTextField.text=dateFormatter.stringFromDate(sender.date)
}
var countryData=[“英国”、“法国”、“西班牙”、“德国”、“柏林”、“Eygpt”、“美国”]
var pickerView:UIPickerView=UIPickerView()
@IBVAR progressStatus:UIProgressView!
@IBVAR barImage:UIImageView!
@IBVAR问题标签:UILabel!
@IBOUTLE var按钮BARIMAGE:UIImageView!
@IBVAR按钮标签:UIButton!
@IBVAR myBackgroundView:UIImageView!
@IBOutlet var questionTextField:UITextField!
让问题=[“你要去哪里?”,“你在那里做什么?”,“你什么时候去?”]
var currentQuestionIndex=0
让占位符=[“国家”、“活动”、“日期”]
var currentPlaceholderIndex=0
@iAction func下一个按钮(发送方:AnyObject){
如果currentQuestionIndex==0{
progressStatus.setProgress(0.333,动画:true)
}如果currentQuestionIndex==1,则为else{
progressStatus.setProgress(0.666,动画:true)
}否则{
progressStatus.setProgress(1,动画:true)
}
//按下按钮时的初始设置
questionTextField.hidden=false
barImage.hidden=false
questionTextField.placeholder=占位符[当前占位符索引]
questionLabel.text=问题[currentQuestionIndex]
questionTextField.resignFirstResponder()辞职
//将文本字段重置为无文本
questionTextField.text=“”
//在数组中显示问题,并在文本字段中显示占位符文本
如果currentQuestionIndex Int{
返回1
}
func pickerView(pickerView:UIPickerView,numberOfRowsInComponent:Int)->Int{
返回countryData.count
}
func pickerView(pickerView:UIPickerView,titleForRow行:Int,forComponent组件:Int)->字符串{
返回国家数据[行]
}
func pickerView(pickerView:UIPickerView,didSelectRow行:Int,不完整组件:Int){
questionTextField.text=国家数据[行]
pickerView.hidden=true
}
//如果用户按下屏幕上的任何位置,则退出键盘
覆盖func touchesBegined(触摸:设置,withEvent事件:UIEvent){
self.view.endEditing(true)
}
重写函数didReceiveMemoryWarning(){
超级。我收到了记忆警告()
//处置所有可以重新创建的资源。
}
}

您必须将VC设置为TextFieldDelegate。这样您就可以对textfields状态做出反应。请参见以下示例类:

class ViewController: UIViewController, UITextFieldDelegate {

  @IBOutlet weak var myTextField: UITextField!
  @IBOutlet weak var myButton: UIButton!

  override func viewDidLoad() {
    super.viewDidLoad()

    // Set the delegate of your textField to this class
    myTextField.delegate = self

    if myTextField.text.isEmpty {
      myButton.userInteractionEnabled = false
    }
  }
  // This method is available, because this class is now the delegate
  func textFieldDidBeginEditing(textField: UITextField) {
    myButton.userInteractionEnabled = true
  }
}
这应该非常类似于你的VC

请注意第一行,VC被告知遵守TextFieldDelegate协议。

编辑:

viewdiload
视图中设置
myButton.userInteractionEnabled=false

设置您的
文本字段
委托

然后

func textFieldDidBeginEditing(textField: UITextField) {
   if !textField.text.isEmpty
       myButton.enable = true

   } else {
       buttonLabel.enable = false
   }
}

您的代码看起来应该与下面类似,假设只有在一个文本字段中有文本时才启用“下一步”按钮,否则您需要相应地更改逻辑

class ViewController: UIViewController, UITextFieldDelegate {

@IBOutlet weak var textField1: UITextField!
@IBOutlet weak var textField2: UITextField!
@IBOutlet weak var textField3: UITextField!
@IBOutlet weak var nextButton: UIButton!

override func viewDidLoad() {
    super.viewDidLoad()
    nextButton.userInteractionEnabled = false
    textField1.delegate = self
    textField2.delegate = self
    textField3.delegate = self
}
@IBAction func NextButtonAction(sender: UIButton)
{
    println("Next Button Tapped")
}
func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
    if textField == textField1
    {
        var oldStr = textField1.text as NSString
        var newStr = oldStr.stringByReplacingCharactersInRange(range, withString: string) as NSString
        if newStr.length == 0
        {
            nextButton.userInteractionEnabled = false
        }else
        {
            nextButton.userInteractionEnabled = true
        }
    }
    return true
}
}

事件应响应编辑更改, 快速版本

@IBAction func editingChanged(textfield: UITextField) {

        myButton.enabled = textfield.text?.characters.count > 0
}

嗨,我已经试过了,但是它不起作用,它仍然让按钮失效。抱歉我错过了上下文,检查编辑。也考虑了。ser按下“下一步”按钮,将显示下一个问题,textfield会自动重置。我像您所说的那样添加了您的代码,它工作了,但这只是第一次。这有意义吗?因此,您需要编写更详细的逻辑,跟踪您从哪个文本字段收集数据,并使您的textFieldDidBeginEditing方法仅为en根据textField参数中指定的文本字段启用next按钮。这是核心或编程-figur