如何在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((,但根本没有运气

这在Swift 5中对我有用:

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

尝试这样:

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)

最新更新