如何在UITextField中将垂直属性文本(自定义占位符字体)居中?

时间:2017-05-30 15:17:55

标签: ios swift uitextfield

我正在使用属性文本属性在UITExtfield中设置自定义占位符字体。但我的占位符文字不是垂直居中的。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)

我尝试添加

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

属性仍然没有运气。我也尝试在我的UITextBox上使用SizeToFit(),但根本没有运气

3 个答案:

答案 0 :(得分:0)

试试这样:

%example(taq,cq_201301)

答案 1 :(得分:0)

这将设置placeholder和用户在中心输入的文本。

 exampleTextField.textAlignment = .center

verticallyhorizontally为中心。

exampleTextField.contentVerticalAlignment = UIControlContentVerticalAlignment.center

exampleTextField.textAlignment = .center

OR

这只会将placeholder设置在中心,而用户输入的文字将保留在其默认位置,即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)

答案 2 :(得分:0)

这在 Swift 5 中对我有用:

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