i want to make the text in center and using spacing
but
i used
textfield.defaultTextAttributes.updateValue(32, forKey: NSAttributedString.Key.kern)
textfield.center = containerView.center
and also align center in xib but the text doesn't become center
is there any other solution?
CodePudding user response:
This issue can be resolve by making the text alignment of textField as center.
You can do this in UIKIT or programmatically also
UiKit:
Programmatically:
txtField.textAlignment = .center
CodePudding user response:
When working with text attributes then use:
let paragraph = NSMutableParagraphStyle()
paragraph.alignment = .center
let attributes = [NSAttributedString.Key.paragraphStyle:paragraph]
let textfield = UITextField()
textfield.defaultTextAttributes = attributes
CodePudding user response:
If you want to keep the kern property every time a character is entered, you need to make a calculation for it. Otherwise, the space between characters will work independently of the center property.
override func viewDidLoad() {
super.viewDidLoad()
tfff.textAlignment = .center
tfff.addTarget(self, action: #selector(textDidChange), for: .editingChanged)
}
@objc func textDidChange(){
guard let count = tfff.text?.count else {
return
}
let paragraph = NSMutableParagraphStyle()
paragraph.alignment = .center
if count != 0 {
let attributedString = NSMutableAttributedString(string: tfff.text!)
attributedString.addAttributes([NSAttributedString.Key.kern : 32], range: NSRange(location: 0, length: count - 1))
attributedString.addAttribute(NSAttributedString.Key.paragraphStyle, value: paragraph, range: NSRange(location: 0, length: count - 1))
tfff.attributedText = attributedString
}
}