Add a button on right view of UItextfield in such way that, text should not overlap the button

前端 未结 7 900
盖世英雄少女心
盖世英雄少女心 2021-01-31 09:07

I can add a button to a textfield on the right hand side of the UITextField using the right view however, the text overlaps on the button. Below is the code for right view butto

7条回答
  •  独厮守ぢ
    2021-01-31 09:12

    Correct answer Swift3+

    If you just override the methods, the text may overlap the right view. This code completely solves this problem.

    You UITextField subclass:

    //...
    
    private func setInsets(forBounds bounds: CGRect) -> CGRect {
    
        var totalInsets = insets //property in you subClass
    
        if let leftView = leftView  { totalInsets.left += leftView.frame.origin.x }
        if let rightView = rightView { totalInsets.right += rightView.bounds.size.width }
    
        return UIEdgeInsetsInsetRect(bounds, totalInsets)
    }
    
    override func textRect(forBounds bounds: CGRect) -> CGRect {
        return setInsets(forBounds: bounds)
    }
    
    override func placeholderRect(forBounds bounds: CGRect) -> CGRect {
        return setInsets(forBounds: bounds)
    }
    
    override func editingRect(forBounds bounds: CGRect) -> CGRect {
        return setInsets(forBounds: bounds)
    }
    
    override func rightViewRect(forBounds bounds: CGRect) -> CGRect {
    
        var rect = super.rightViewRect(forBounds: bounds)
        rect.origin.x -= insets.right
    
        return rect
    }
    
    override func leftViewRect(forBounds bounds: CGRect) -> CGRect {
    
        var rect = super.leftViewRect(forBounds: bounds)
        rect.origin.x += insets.left
    
        return rect
    }
    

提交回复
热议问题