iosswiftphonenumberkit

How can I add an inset to the text and placeholder in PhoneNumberTextField


I need to use a textfield to havet he user type in phone numbers so I'm using the PhoneNumberTextField from the project PhoneNumberKit.

By default it's just a borderless textfield. I modified it by adding a border with a corner radius and a UIButton added to its leftView. The problem with that is the text/placeholder is shown right up against the border.

enter image description here

enter image description here

I tried subclassing PhoneNumberTextField and adding the text inset capability like this.

@IBDesignable
class CNPhoneNumberTextField: PhoneNumberTextField {
    @IBInspectable var inset: CGFloat = 0

    override func textRect(forBounds bounds: CGRect) -> CGRect {
        return bounds.insetBy(dx: inset, dy: inset)
    }

    override func editingRect(forBounds bounds: CGRect) -> CGRect {
        return bounds.insetBy(dx: inset, dy: inset)
    }

    override func placeholderRect(forBounds bounds: CGRect) -> CGRect {
        return bounds.insetBy(dx: inset, dy: inset)
    }
}

The issue here is it doesn't take the leftView into account now. The text/placeholder is partially covered by the leftView.

enter image description here

Is there any other way to fix this?

Demo project


Solution

  • You need to update your CNPhoneNumberTextField class like shown below where you can give leftPadding for your textField from storyboard.

    Your class will look like:

    import UIKit
    import PhoneNumberKit
    
    @IBDesignable
    class CNPhoneNumberTextField: PhoneNumberTextField {
    
        @IBInspectable var leftPadding: CGFloat = 0
    
        override open func textRect(forBounds bounds: CGRect) -> CGRect {
    
            let padding = UIEdgeInsets(top: 0, left: leftPadding, bottom: 0, right: 0)
            return bounds.inset(by: padding)
        }
    
        override open func placeholderRect(forBounds bounds: CGRect) -> CGRect {
    
            let padding = UIEdgeInsets(top: 0, left: leftPadding, bottom: 0, right: 0)
            return bounds.inset(by: padding)
        }
    
        override open func editingRect(forBounds bounds: CGRect) -> CGRect {
    
            let padding = UIEdgeInsets(top: 0, left: leftPadding, bottom: 0, right: 0)
            return bounds.inset(by: padding)
        }
    }
    

    And from storyboard with Attribute inspector section you can assign left padding like:

    enter image description here

    And your result will be:

    enter image description here

    Reference from THIS answer.

    EDIT:

    HERE is the demo project.