我想在 UITextField 的开头留一点空间,就像这里一样: Add lefthand margin to UITextField
但我不知道如何用 Swift 做到这一点。
这就是我现在正在使用的:
斯威夫特 4.2
class TextField: UITextField { let padding = UIEdgeInsets(top: 0, left: 5, bottom: 0, right: 5) override open func textRect(forBounds bounds: CGRect) -> CGRect { return bounds.inset(by: padding) } override open func placeholderRect(forBounds bounds: CGRect) -> CGRect { return bounds.inset(by: padding) } override open func editingRect(forBounds bounds: CGRect) -> CGRect { return bounds.inset(by: padding) } }
斯威夫特 4
class TextField: UITextField { let padding = UIEdgeInsets(top: 0, left: 5, bottom: 0, right: 5) override open func textRect(forBounds bounds: CGRect) -> CGRect { return UIEdgeInsetsInsetRect(bounds, padding) } override open func placeholderRect(forBounds bounds: CGRect) -> CGRect { return UIEdgeInsetsInsetRect(bounds, padding) } override open func editingRect(forBounds bounds: CGRect) -> CGRect { return UIEdgeInsetsInsetRect(bounds, padding) } }
斯威夫特 3:
class TextField: UITextField { let padding = UIEdgeInsets(top: 0, left: 5, bottom: 0, right: 5) override func textRect(forBounds bounds: CGRect) -> CGRect { return UIEdgeInsetsInsetRect(bounds, padding) } override func placeholderRect(forBounds bounds: CGRect) -> CGRect { return UIEdgeInsetsInsetRect(bounds, padding) } override func editingRect(forBounds bounds: CGRect) -> CGRect { return UIEdgeInsetsInsetRect(bounds, padding) } }
我从来没有设置其他填充,但你可以调整。此类不处理文本字段上的 rightView 和 leftView。如果您希望正确处理它,您可以使用类似(objc 中的示例,我只需要 rightView:
- (CGRect)textRectForBounds:(CGRect)bounds { CGRect paddedRect = UIEdgeInsetsInsetRect(bounds, self.insets); if (self.rightViewMode == UITextFieldViewModeAlways || self.rightViewMode == UITextFieldViewModeUnlessEditing) { return [self adjustRectWithWidthRightView:paddedRect]; } return paddedRect; } - (CGRect)placeholderRectForBounds:(CGRect)bounds { CGRect paddedRect = UIEdgeInsetsInsetRect(bounds, self.insets); if (self.rightViewMode == UITextFieldViewModeAlways || self.rightViewMode == UITextFieldViewModeUnlessEditing) { return [self adjustRectWithWidthRightView:paddedRect]; } return paddedRect; } - (CGRect)editingRectForBounds:(CGRect)bounds { CGRect paddedRect = UIEdgeInsetsInsetRect(bounds, self.insets); if (self.rightViewMode == UITextFieldViewModeAlways || self.rightViewMode == UITextFieldViewModeWhileEditing) { return [self adjustRectWithWidthRightView:paddedRect]; } return paddedRect; } - (CGRect)adjustRectWithWidthRightView:(CGRect)bounds { CGRect paddedRect = bounds; paddedRect.size.width -= CGRectGetWidth(self.rightView.frame); return paddedRect; }