簡體   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