1, problem descriptionSometimes we need to initially set the "Confirm" button to be unavailable when we develop, and then make the input button available after entering text in the text box.
2, the principle of implementation(1) To detect changes in the contents of the text box, we need to have the controller of the new interface follow a text protocol uitextfielddelegate. Also set the proxy for the text box to mainlistcontroller the current instance within the Viewdidload method. Then implement Textfile's Shouldchangecharactersinrange method to execute some code when the text box is going to change. (2) But this is only going to change when executed, not after the change. For example, in this method to print out the contents of the text box, you will find that whenever we change the contents of the text box, the print is the last content. For example, first enter 1, print out is empty. Then enter 2, the text box is 12, but the print is 1. To get the latest content, you need the Stringbyreplacingcharactersinrange method of string, but this method is not supported in Swift's string. To solve this problem, we should make an extension for nsrange first.
3, the code is as follows
| 123456789101112131415161718192021222324252627282930313233343536 |
import UIKit class ViewController: UIViewController ,UITextFieldDelegate{ @IBOutlet weak var button: UIButton! @IBOutlet weak var textField: UITextField! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. textField.delegate = self } func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool { let newText = textField.text .stringByReplacingCharactersInRange(range.toRange(textField.text), withString: string) button.enabled = countElements(newText) > 0 return true } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. }}//扩展NSRange,让swift的string能使用stringByReplacingCharactersInRangeextension NSRange { func toRange(string: String) -> Range<String.Index> { let startIndex = advance(string.startIndex, self.location) let endIndex = advance(startIndex, self.length) return startIndex..<endIndex }} |
Swift-The text input box responds when content changes and gets the latest content