【问题标题】:How to center vertically attributed text (custom placeholder font) in UITextField?如何在 UITextField 中居中垂直属性文本(自定义占位符字体)?
【发布时间】:2021-05-05 19:21:37
【问题描述】:

我正在使用属性文本属性在 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() 但一点运气都没有

【问题讨论】:

  • .alignment = .center,用于左/右/居中,水平对齐,而不是垂直对齐。检查:stackoverflow.com/questions/3665385/…contentVerticalAlignment
  • 你发现了吗?如果是,请发布答案。

标签: ios swift uitextfield


【解决方案1】:

这在 Swift 5 中对我有用:

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

【讨论】:

    【解决方案2】:

    试试这样:

    let centeredParagraphStyle = NSMutableParagraphStyle()
    centeredParagraphStyle.alignment = .center
    
    let attributes: [String : Any] = [NSParagraphStyleAttributeName: centeredParagraphStyle]
    

    【讨论】:

    • 谢谢,我已经试过了,忘记在帖子中放置我将该样式与其他属性一起放入属性中的行。仍然没有运气:(
    【解决方案3】:

    这将设置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)
    

    【讨论】:

    • 我的占位符需要垂直居中。您可以在图片上看到占位符靠近顶部,而不是在中间
    猜你喜欢
    • 2013-09-13
    • 2011-07-23
    • 2012-01-23
    • 2012-07-17
    • 1970-01-01
    • 2023-04-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多