I'd like to change the color of "00" to gray and change the color of fix "555" to make black in my UITextField. How can i do ? Thank you for your guidance.
var placeHolder = "00"
func textFieldDidBeginEditing(_ textField: UITextField) {
if inputCoupon.text == self.placeHolder {
inputCoupon.text = "00"
}
}
func textFieldDidEndEditing(_ textField: UITextField) {
if inputCoupon.text == "00" {
textField.text = self.placeHolder
}
}
@objc func textFieldDidChange(_ textField: UITextField) {
let intTmp:Int = Int("\(textField.text ?? "00")") ?? 00
sliderBarInputCoupon.setValue(Float(intTmp), animated:true)
let setLabel:Int = Int(intTmp)
let payCou = setLabel * 2
let xCoupon = Double(payCou) * 0.15
let reWard = Int(payCou) - Int(xCoupon)
let calReward = String(reWard)
rewardCoupon.text = "Reward :\(calReward)"
rewardCoupon.adjustsFontSizeToFitWidth = true
}
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool{
let currentText = textField.text ?? ""
guard let stringRange = Range(range, in: currentText) else{
return false
}
let updateText = currentText.replacingCharacters(in: stringRange, with: string)
return updateText.count < 6
}
CodePudding user response:
- Create string extension for change text color
extension String
func attributedValue(_ value:String, _ color:UIColor) -> NSMutableAttributedString {
let attributedString: NSMutableAttributedString = NSMutableAttributedString(string: self)
attributedString.setColor(color: color, forText: value)
return attributedString
}
- Create NSMutableAttributedString Extension for find string range
extension NSMutableAttributedString
func setColor(color: UIColor, forText stringValue: String) {
let range: NSRange = self.mutableString.range(of: stringValue, options: .caseInsensitive)
self.addAttribute(NSAttributedString.Key.foregroundColor, value: color, range: range)
}
- How to use this code ?
textfield.text = "5500"
textfield.text.attributedValue("00", UIColor.red)
Above example will change the color of the "00" string