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

前端 未结 7 826
盖世英雄少女心
盖世英雄少女心 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:11

    You can achieve same as shown below:

    @IBOutlet weak var textField: UITextField!
    
    var textFieldBtn: UIButton {
        let button = UIButton(type: .custom)
        button.setImage(UIImage(named: "image.png"), for: .normal)
        button.imageEdgeInsets = UIEdgeInsetsMake(0, 0, 0, 0)
        button.frame = CGRect(x: CGFloat(textField.frame.size.width - 40), y: CGFloat(5), width: CGFloat(40), height: CGFloat(30))
        button.backgroundColor = UIColor.darkGray
        button.addTarget(self, action: #selector(self.refreshContent), for: .touchUpInside)
    
        return button
    }
    
    func refreshContent() {
    
        // Add your code here to handle button.
    }
    

    Add to textField.

    textField.rightView = textFieldBtn
    textField.rightViewMode = .always
    

提交回复
热议问题