如何解决在文本字段内发出居中占位符
本质上,当没有文本存在时,我有一个文本字段的以下代码在右侧显示一个按钮,我还有一些用于显示偏离中心的文本字段的占位符文本文本。无论如何,当 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
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。