1
votes

I am using attributed text property to set custom placeholder font in UITExtfield. But my placeholder text is not vertically centered.Here is preview

        let font = UIFont(name: Font.myFont.name, size: 15)!
        let attributes = [
            NSForegroundColorAttributeName: UIColor.cadetGrey,
            NSFontAttributeName: font
        ]

        exampleTextField.attributedPlaceholder = NSAttributedString(string: "Example Placeholder",
                                                                  attributes: attributes)

I tried to add

let centeredParagraphStyle = NSMutableParagraphStyle()
centeredParagraphStyle.alignment = .center

to attribute still no luck. I also tried to use SizeToFit() on my UITextBox but no luck at all

3
.alignment = .center, that's for left/right/center, horizontal alignment, not vertical one. Check that: stackoverflow.com/questions/3665385/… contentVerticalAlignmentLarme
Did you figure this out? If yes, please post the answer.Tejas K

3 Answers

0
votes

Try like this :

let centeredParagraphStyle = NSMutableParagraphStyle()
centeredParagraphStyle.alignment = .center

let attributes: [String : Any] = [NSParagraphStyleAttributeName: centeredParagraphStyle]
0
votes

This is will set both placeholder and text input by user in center.

 exampleTextField.textAlignment = .center

To center both vertically and horizontally.

exampleTextField.contentVerticalAlignment = UIControlContentVerticalAlignment.center

exampleTextField.textAlignment = .center

OR

This is will only set placeholder in center whereas the text input by user will remain at it's default position i.e left align

let font = UIFont(name: Font.myFont.name, size: 15)!

 let centeredParagraphStyle = NSMutableParagraphStyle()
 centeredParagraphStyle.alignment = .center

 // add attribute of NSMutableParagraphStyle
 let attributes = [
            NSForegroundColorAttributeName: UIColor.gray,
            NSFontAttributeName: font,
            NSParagraphStyleAttributeName: centeredParagraphStyle
        ]

 exampleTextField.attributedPlaceholder = NSAttributedString(string: "Example Placeholder",
                                                                    attributes: attributes)
0
votes

This worked for me in Swift 5:

let unitText = NSAttributedString(string: "\(unit)", attributes: [NSAttributedString.Key.foregroundColor: MyColors.doveGray, NSAttributedString.Key.baselineOffset:2])