Swift:如何使用UISwitch控制使用委托启用或禁用UITextField

时间:2015-06-28 00:42:09

标签: ios swift delegates uiswitch uitextfielddelegate

XCode 6.3.2中,我有一个UITextField:

@IBOutlet weak var uiswitchControlledTextField: UITextField!

我现在使用UISwitch(名为mySwitch)以下列方式控制其启用或禁用状态:

@IBOutlet weak var mySwitch: UISwitch!
mySwitch.addTarget(self, action: Selector("stateChanged:"), forControlEvents: UIControlEvents.ValueChanged)

//callback below:
func stateChanged(switchState: UISwitch) {
        uiswitchControlledTextField.enabled = switchState.on

    }

以上情况很好,但是,我希望尝试创建一个UITextFieldDelegate以同样的方式控制上面的UITextField。到目前为止,我通过实现textFieldShouldBeginEditing得到以下内容,其中我希望返回false以禁用UITextField,但我不知道如何让UISwitch动态返回 true textFieldShouldBeginEditing

的strong>或 false
import Foundation
import UIKit

class SwitchControlledTextFieldDelegate: NSObject, UITextFieldDelegate {

    func textFieldShouldBeginEditing(textField: UITextField) -> Bool {
        return false; //do not show keyboard or cursor
    }

}

在ViewController中,我尝试设置

self.uiswitchControlledTextField.delegate = SwitchControlledTextFieldDelegate()

但它并不像我希望的那样有效。任何帮助将不胜感激。

2 个答案:

答案 0 :(得分:0)

self.uiswitchControlledTextField.delegate = SwitchControlledTextFieldDelegate()

问题是该行只是创建了一个SwitchControlledTextFieldDelegate类的实例,然后立即重新出现。

你需要使用一些已经存在且会持续存在的实例作为你的文本字段委托,或者像你的视图控制器一样!

答案 1 :(得分:0)

(Xcode 7) 使用此:

override func viewDidLoad() {
    super.viewDidLoad()
    // Setting the delegate
    self.textField3.delegate = self

    self.editingSwitch.setOn(false, animated: false)
} 
// Text Field Delegate Methods
func textFieldShouldBeginEditing(textField: UITextField) -> Bool {
    return self.editingSwitch.on
}
@IBAction func toggleTheTextEditor(sender: AnyObject) {
    if !(sender as! UISwitch).on {
        self.textField3.resignFirstResponder()
    }
}