Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift 4 - UITextfield border radius color issue

I'm currently experimenting with UITextfields (I'm a beginner). Right now I have set the background color of my application and set the border radius but there's a small issue I'm encountering while doing this.

My code:

        superView.backgroundColor = backgroundColorrr
        loginView.backgroundColor = backgroundColorrr

        loginLabel.textColor = UIColor.white
        loginLabel.text = "Login"

        loginButton.layer.cornerRadius = 5
        loginButton.layer.borderWidth = 2.0
        loginButton.imageView?.contentMode = UIViewContentMode.scaleToFill
        loginButton.layer.borderColor = UIColor.lightGray.cgColor
        loginButton.layer.backgroundColor = backgroundColorrr.cgColor
        loginButton.titleLabel?.textColor = UIColor.white
        loginButton.titleLabel?.text = "Login"

        userNameTextField.layer.cornerRadius = 15.0
        userNameTextField.layer.backgroundColor = backgroundColorrr.cgColor
        userNameTextField.layer.borderWidth = 0.5

My result:

current layout in simulator

You see what I'm trying to achieve is to have the same background color as the rest of my screen (I don't want the white color next to the textfield's border. Same goes with my button, the border radius won't change at all (image used has the same size as the size of my button.

Any help is welcome!

like image 674
Mathias Schrooten Avatar asked Nov 18 '17 15:11

Mathias Schrooten


1 Answers

You need to set layer.masksToBounds = true if you want to apply cornerRadius.

Set userNameTextField.layer.masksToBounds = true and loginButton.layer.masksToBounds = true

Your full code should look like this:

superView.backgroundColor = backgroundColorrr
loginView.backgroundColor = backgroundColorrr

loginLabel.textColor = UIColor.white
loginLabel.text = "Login"

loginButton.layer.masksToBounds = true
loginButton.layer.cornerRadius = 5
loginButton.layer.borderWidth = 2.0
loginButton.imageView?.contentMode = UIViewContentMode.scaleToFill
loginButton.layer.borderColor = UIColor.lightGray.cgColor
loginButton.layer.backgroundColor = backgroundColorrr.cgColor
loginButton.titleLabel?.textColor = UIColor.white
loginButton.titleLabel?.text = "Login"

userNameTextField.layer.masksToBounds = true
userNameTextField.layer.cornerRadius = 15.0
userNameTextField.layer.backgroundColor = backgroundColorrr.cgColor
userNameTextField.layer.borderWidth = 0.5

Note: You can achieve the "same" results on cornerRadius if you apply clipsToBounds = true.

like image 167
Gustavo Vollbrecht Avatar answered Oct 19 '22 17:10

Gustavo Vollbrecht