占位符文本不在iOS中居中

时间:2018-02-17 09:48:39

标签: ios swift

我创建了带圆角的文本字段。光标的位置以及键入文本时都可以。但占位符文本已关闭。占位符位置是否有一种方法可以跟随文本字段。

下面的代码覆盖了UITextField函数以重新定位游标。

override func textRect(forBounds bounds: CGRect) -> CGRect {
    return CGRect(x: 0 + textOffset,
                  y: 0 + (textOffset / 2),
                  width: self.frame.width - textOffset,
                  height: self.frame.height + textOffset)
}

override func editingRect(forBounds bounds: CGRect) -> CGRect {
    return CGRect(x: 0 + textOffset,
                  y: 0 + (textOffset / 2),
                  width: self.frame.width - textOffset,
                  height: self.frame.height + textOffset)

This is the offset shown on the image

3 个答案:

答案 0 :(得分:0)

使用此覆盖方法设置placeholderRect

override func placeholderRect(forBounds bounds: CGRect) -> CGRect {
    return UIEdgeInsetsInsetRect(bounds, paddingInsets)
}

答案 1 :(得分:0)

您可以使用attributedPlaceholder段落样式,您可以将占位符置于UITextField中心。

let textField = UITextField(frame: CGRect(x: 0, y: 100, width: self.view.frame.size.width, height: 60))
textField.backgroundColor = UIColor.gray
let centeredParagraphStyle = NSMutableParagraphStyle()
centeredParagraphStyle.alignment = .center
let attributedPlaceholder = NSAttributedString(string: "Placeholder", attributes: [NSAttributedStringKey.paragraphStyle: centeredParagraphStyle])
textField.attributedPlaceholder = attributedPlaceholder

答案 2 :(得分:0)

对我有用的是创建 baselineOffset 属性,然后设置 attributedPlaceholder

    let attributes = [NSAttributedString.Key.baselineOffset : NSNumber(2.0)]

myTextField.attributedPlaceholder = NSAttributedString(string: "Placeholder", attributes: attributes)