更改 UITextfield 输入的宽度

Change Width of UITextfield Input

有没有办法更改我的 UITextield 的输入大小,使其不与我的 "vergessen"-Button 重叠?

Textfield 是一个宽度为 315 的简单 TextfieldView。我使用下面的代码以编程方式添加了 "Vergessen?" 按钮。

func createForgetButton () {
    let button = UIButton(type: .system)
    button.setTitle("Vergessen?", for: .normal)
    button.addTarget(self, action: #selector(self.vergessenTapped(_:)), for: .touchUpInside)
    button.titleLabel?.font = UIFont(name: "Avenir Next", size: 19.0)
    passwordTextField.rightView = button
    passwordTextField.rightViewMode = .unlessEditing
}

对该字段使用以下自定义 class。然后更新 IB 或代码中的 .rightPadding 字段以匹配右侧按钮的宽度。

/**
 * Text field with some changes according to design
 *
 * - author: Alexander Volkov
 * - version: 1.0
 */
@IBDesignable public class CustomTextField: UITextField {

    /// the left padding
    @IBInspectable public var leftPadding: CGFloat = 0 { didSet { self.setNeedsLayout() } }

    /// the right padding
    @IBInspectable public var rightPadding: CGFloat = 0 { didSet { self.setNeedsLayout() } }

    /// Text rectangle
    ///
    /// - Parameter bounds: the bounds
    /// - Returns: the rectangle
    override public func textRect(forBounds bounds: CGRect) -> CGRect {
        let originalRect: CGRect = super.editingRect(forBounds: bounds)
        return CGRect(x: originalRect.origin.x + leftPadding, y: originalRect.origin.y, width: originalRect.size.width - leftPadding - rightPadding, height: originalRect.size.height)
    }

    /// Editing rectangle
    ///
    /// - Parameter bounds: the bounds
    /// - Returns: the rectangle
    override public func editingRect(forBounds bounds: CGRect) -> CGRect {
        let originalRect: CGRect = super.editingRect(forBounds: bounds)
        return CGRect(x: originalRect.origin.x + leftPadding, y: originalRect.origin.y, width: originalRect.size.width - leftPadding - rightPadding, height: originalRect.size.height)
    }
}