繁体   English   中英

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

[英]How to center vertically attributed text (custom placeholder font) in UITextField?

我正在使用属性文本属性在UITExtfield中设置自定义占位符字体。 但是我的占位符文本不是垂直居中。 这是预览

        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(),但没有运气

尝试这样:

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

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

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

 exampleTextField.textAlignment = .center

使verticallyhorizontally居中。

exampleTextField.contentVerticalAlignment = UIControlContentVerticalAlignment.center

exampleTextField.textAlignment = .center

要么

这只会将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)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM