斯威夫特 3
不要忘记accessory views
UITextField 的。如果您想要一个有效的实现,您需要考虑super
*rect(forBounds: ...) 函数。并且还要确保只替换越野车的矩形iOS 10
而不是 9 或 8!以下代码应该可以解决问题:
public class CustomTextField: UITextField {
public override func textRect(forBounds bounds: CGRect) -> CGRect {
let superValue = super.textRect(forBounds: bounds)
if #available(iOS 10, *) {
return superValue.insetBy(dx: 0, dy: 0)
}
return superValue
}
public override func editingRect(forBounds bounds: CGRect) -> CGRect {
let superValue = super.editingRect(forBounds: bounds)
if #available(iOS 10, *) {
return superValue.insetBy(dx: 0, dy: -0.5)
}
return superValue
}
public override func placeholderRect(forBounds bounds: CGRect) -> CGRect {
let superValue = super.placeholderRect(forBounds: bounds)
if #available(iOS 10, *) {
if isEditing {
return superValue.insetBy(dx: 0, dy: 0.5)
}
return superValue.insetBy(dx: 0, dy: 0.0)
}
return superValue
}
}
编辑
我从上面稍微编辑了我的代码到下面,它对我来说效果更好。我在 iPhone 6、6s、7、7s 以及 iOS 9.3 和 10.3 的“加号”设备上测试它。
public class CustomTextField: UITextField {
public override func textRect(forBounds bounds: CGRect) -> CGRect {
let superValue = super.textRect(forBounds: bounds)
if #available(iOS 10, *) {
return superValue.insetBy(dx: 0, dy: -0.3)
}
return superValue.insetBy(dx: 0, dy: -0.2)
}
public override func editingRect(forBounds bounds: CGRect) -> CGRect {
return self.textRect(forBounds: bounds)
}
}
我认为这也取决于您使用的字体。我用UIFont.systemFont(ofSize: 17.0, weight: UIFontWeightLight)