简体   繁体   中英

Change Width of UITextfield Input

Is there a way to change the input size of my UITextield so it doesn't overlap with my "vergessen"-Button?

The Textfield is a simple TextfieldView with a width of 315. I added the "Vergessen?" Button programmatically with the code down below.

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
}

在此处输入图片说明

Use the following custom class for the field. Then update .rightPadding field in IB or in the code to match the width of the button you have on the right.

/**
 * 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)
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM