pankaj pankaj - 1 year ago 146
Swift Question

Create semi transparent uibutton with solid white text

I am trying to create button similar to following:
enter image description here

I have tried to give alpha with white text color but I am getting following:

enter image description here


textfield.backgroundColor = UIColor(red: 0.7, green: 0.7, blue: 0.7, alpha: 0.7)
textfield.textColor = .white

Above code gives second image. But above image looks ugly.

How can I create uitextfield like first image?


Complete Solution:

txtLogin.backgroundColor = UIColor(red: 1, green: 1, blue: 1, alpha: 0.1)
txtLogin.textColor = .white
txtLogin.attributedPlaceholder = NSAttributedString(string:"Username",
attributes:[NSForegroundColorAttributeName: UIColor(red: 245, green: 245, blue: 241, alpha: 0.7)])
let paddingView = UIView(frame: CGRect(x: 0, y: 0, width: 10, height: 20))
txtLogin.leftView = paddingView
txtLogin.leftViewMode = UITextFieldViewMode.always

let layer: CALayer! = txtLogin.layer
layer.cornerRadius = 4.0
layer.borderWidth = 0


Answer Source

What you need to do is set the alpha of the button to the point that you want. So for example this would have a semi-transparent background and white text color:

button.backgroundColor = UIColor(red: 1, green: 1, blue: 1, alpha: 0.1)
button.textColor = .white
button.attributedPlaceholder = NSAttributedString(string:"placeholder text",
                                                   attributes:[NSForegroundColorAttributeName: UIColor.white])
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download