标签:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
|
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能使用stringByReplacingCharactersInRange extension NSRange { func toRange(string: String ) -> Range < String . Index > { let startIndex = advance (string.startIndex, self .location) let endIndex = advance (startIndex, self .length) return startIndex..<endIndex } } |
标签:
原文地址:http://www.cnblogs.com/Free-Thinker/p/4841061.html