How do you create textfield padding in Swift 4?

后端 未结 3 1821
太阳男子
太阳男子 2021-02-06 04:59

I have a textfield called

nameTextField

I rounded the corners with the

nameTexfield.layer.cornerRadius = 5

3条回答
  •  长发绾君心
    2021-02-06 05:19

    Customized way to add padding in "left", "right" or "both" side od UITextField.

    Step 1:- Add this UITextfield extension

    extension UITextField {
    
        enum PaddingSide {
            case left(CGFloat)
            case right(CGFloat)
            case both(CGFloat)
        }
    
        func addPadding(_ padding: PaddingSide) {
    
            self.leftViewMode = .always
            self.layer.masksToBounds = true
    
    
            switch padding {
    
            case .left(let spacing):
                let paddingView = UIView(frame: CGRect(x: 0, y: 0, width: spacing, height: self.frame.height))
                self.leftView = paddingView
                self.rightViewMode = .always
    
            case .right(let spacing):
                let paddingView = UIView(frame: CGRect(x: 0, y: 0, width: spacing, height: self.frame.height))
                self.rightView = paddingView
                self.rightViewMode = .always
    
            case .both(let spacing):
                let paddingView = UIView(frame: CGRect(x: 0, y: 0, width: spacing, height: self.frame.height))
                // left
                self.leftView = paddingView
                self.leftViewMode = .always
                // right
                self.rightView = paddingView
                self.rightViewMode = .always
            }
        }        
    }
    

    Step 2: How to use

    // 1.  To add left padding
    yourTextFieldName.addPadding(.left(20)) 
    
    // 2.  To add right padding
    yourTextFieldName.addPadding(.right(20))
    
    // 3. To add left & right padding both
    yourTextFieldName.addPadding(.both(20))
    

提交回复
热议问题