UITextField And UILabel Tips

UITextField Tips

Add a top Line on Keyboard

1
2
3
4
5
6
7
8
extension UITextField {
func addTopLineOnKeyboard() {
let line = UIView(frame: CGRect(x: 0, y: 0, width: 2000, height: 0.5))
line.backgroundColor = "979797".color

inputAccessoryView = line
}
}

Only allowed a price number with exactly two decimals

1
2
3
4
5
6
7
8
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
let str = (textField.text! as NSString).replacingCharacters(in: range, with: string)

let regex = "^([1-9]\\d{0,7}|0)(\\.\\d{0,2})?$|^$"
let predicte = NSPredicate(format: "SELF MATCHES %@", regex)

return predicte.evaluate(with: str)
}

Only allowed 1-100 or leave blank

1
2
3
4
5
6
7
8
9
10
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {

let str = (textField.text! as NSString).replacingCharacters(in: range, with: string)

// 1-100 or leave blank
let regex = "^[1-9]?\\d|100|[1-9]?$"
let predicte = NSPredicate(format: "SELF MATCHES %@", regex)

return predicte.evaluate(with: str)
}

UILabel Tips

Formate cell-phone number to 111 1111 111

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
extension String {
var phoneNumberFormater: String {
get {
var s = self.replacingOccurrences(of: " ", with: "")
let count = s.characters.count
if count > 7 {
s.insert(" ", at: s.index(s.startIndex, offsetBy: 3))
s.insert(" ", at: s.index(s.startIndex, offsetBy: 8))
} else if count > 3 {
s.insert(" ", at: s.index(s.startIndex, offsetBy: 3))
}
return s
}
}
}

Highlight UILabel’s substring by given string

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
var userInputPhoneNumber = "123"

@IBOutlet private weak var phoneLabel: UILabel!

var phoneNumber: String = "123456789" {
didSet {
let atrStr = NSMutableAttributedString(string: phoneNumber.phoneNumberFormater)

let font = UIFont.systemFont(ofSize: 14)
let range = (phoneNumber.phoneNumberFormater as NSString).range(of: userInputPhoneNumber.phoneNumberFormater)

if range.location == 0 {
atrStr.addAttributes([NSFontAttributeName : font, NSForegroundColorAttributeName: UIColor.red], range: (phoneNumber.phoneNumberFormater as NSString).range(of: userInputPhoneNumber.phoneNumberFormater))
}

phoneLabel.attributedText = atrStr
}
}