Content of UITextFiled gets trimmed when removing the border

自古美人都是妖i 提交于 2019-12-08 09:52:18

问题


For my UITextField, I want the border to be removed. So, I tried changing its border color to the background color (with border width of 1) but doing so, faint border lines are seen at the corners. Next, I set the border style to none in the attribute inspector. When I run the app, the border is gone. However, when the text is entered in it, the text gets cropped in the left side as shown in the image. I tried adding padding view to the textfield but it did not fix the issue. How can I solve this?

EDIT:

The textfield is followed by a label. Since I want the label to follow the textfield content, I have not set the width of the textfield. This is shown in the image. When I add padding view with leftViewMode as always, the design in not rendered, and i get the console message:

- changing property masksToBounds in transform-only layer, will have no effect

Following one of the answers from @Surjeet's link, I tried extending the textField as:

class CustomTextField: UITextField {

    required init?(coder aDecoder: NSCoder){
        super.init(coder: aDecoder)
    }

    override func textRect(forBounds bounds: CGRect) -> CGRect {
        return CGRect(x: bounds.origin.x + 10, y: bounds.origin.y, width: bounds.size.width, height: bounds.size.height)
    }

    override func editingRect(forBounds bounds: CGRect) -> CGRect {
        return self.textRect(forBounds: bounds)
    }
}

But still the problem is not solved.


回答1:


You can add left padding for your textfield and your issue should be resolved.

Swift 4

        let paddingView: UIView = UIView.init(frame: CGRect(x: 0, y: 0, width: 5, height: 20))
        textField.leftView = paddingView
        textField.leftViewMode = .always



回答2:


text_field.setLeftPaddingPoints(10)

text_field.setRightPaddingPoints(10)


extension UITextField {

    func setLeftPaddingPoints(_ amount:CGFloat){
       let paddingView = UIView(frame: CGRect(x: 0, y: 0, width: amount, height: self.frame.size.height))
       self.leftView = paddingView
       self.leftViewMode = .always
    }
    func setRightPaddingPoints(_ amount:CGFloat) {
      let paddingView = UIView(frame: CGRect(x: 0, y: 0, width: amount, height: self.frame.size.height))
      self.rightView = paddingView
      self.rightViewMode = .always
    }
}


来源:https://stackoverflow.com/questions/48635339/content-of-uitextfiled-gets-trimmed-when-removing-the-border

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!