Mathias Schrooten
Mathias Schrooten

Reputation: 732

Swift 4 - UITextfield border radius color issue

I'm currently experimenting with UITextfield (I'm a beginner). Right now I have set the background color of my app 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!

Upvotes: 6

Views: 5397

Answers (1)

Gustavo Vollbrecht
Gustavo Vollbrecht

Reputation: 3256

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.

Upvotes: 15

Related Questions