在文本字段内发布居中占位符

Issue centering placeholder inside a textfield

基本上我有以下文本字段代码,当没有文本存在时在右侧显示一个按钮,我还有一些文本字段的占位符文本文本显示偏离中心。当 rightViewMode 中有一个按钮时,有没有办法让占位符文本保持居中?

let centeredParagraphStyle = NSMutableParagraphStyle()
    centeredParagraphStyle.alignment = .center
    let attributedPlaceholder = NSAttributedString(string: "Scan", attributes: [NSAttributedString.Key.paragraphStyle: centeredParagraphStyle])
serialTF.attributedPlaceholder = attributedPlaceholder
let wSize = serialTF.frame.size.height - 2
let scanSerialButton = UIButton( type: .custom )
scanSerialButton.setImage(UIImage(named: "barcodeScan"), for: .normal )
scanSerialButton.addTarget( self, action: #selector(scanSerial), for: .touchUpInside )
scanSerialButton.frame = CGRect( x: wSize, y: 0, width: wSize, height: wSize )
let wV = UIView()
wV.frame = CGRect( x:0, y:0, width: wSize * 2, height: wSize )
wV.addSubview(scanSerialButton)
serialTF.rightView = wV;
serialTF.rightViewMode = .unlessEditing;

您可以子类化 UITextField,它将提供一个像这样自定义占位符框架的机会。

class CustomTextField: UITextField {
    override func placeholderRect(forBounds bounds: CGRect) -> CGRect {
        // return what you want from here
    }
}

不要在视图中嵌入按钮,将按钮直接分配给 rightView

txtField.rightView = scanSerialButton