我正在尝试添加“错误消息”气泡,当用户输入错误的值时,该气泡会出现在文本字段的顶部。我一直在使用.leftView属性工作正常,但它占用textField中的“空格”,将内容推向右侧。将leftView显示为“叠加”而不是字段本身的最佳方法是什么? (即删除它的界限)
class ValidatedTextField: UITextField {
override init(frame: CGRect) {
super.init(frame: frame)
// Defaults
maxLength = 40
layer.sublayerTransform = CATransform3DMakeTranslation(leftPadding, 0, 0)
backgroundColor = UIColor.whiteColor()
// Listen in on own text input
self.addTarget(self, action: "textHasChanged", forControlEvents: UIControlEvents.EditingChanged)
self.addTarget(self, action: "checkTextValid", forControlEvents: UIControlEvents.EditingDidEnd)
}
override func layoutSubviews() {
super.layoutSubviews()
// Add error label message
labelMessage.frame = CGRectMake(10-leftPadding, -10, self.bounds.size.width-20, 24)
labelMessage.backgroundColor = .blackColor()
labelMessage.text = "Message goes here"
labelMessage.font = UIFont.boldSystemFontOfSize(16)
labelMessage.textColor = .whiteColor()
labelMessage.textAlignment = .Center
labelMessage.layer.cornerRadius = 8
self.leftView = labelMessage
self.leftViewMode = .Always
}
}
答案 0 :(得分:-1)
所以我想我已经明白了。通过使用leftViewRectForBounds并返回零CGRect,我能够消除它的物理存在。
override func leftViewRectForBounds(bounds: CGRect) -> CGRect {
return CGRect(x: 0, y: 0, width: 0, height: 0)
}