KTOV
KTOV

Reputation: 704

Swift - Changing background color to transparent

I noticed one of my buttons has a value for the background color = 'default'

When the button is highlighted I want to change a different button to also have a 'default' background color, here is my code so far:

@IBAction func buttonTouchUpInside(_ sender: UIButton) {

    registerBtn.setTitleColor(UIColor.white, for: UIControlState.highlighted);
}

How do I achieve this so registerBtn has a background color which is basically transparent?

Upvotes: 8

Views: 18141

Answers (3)

Akbar Khan
Akbar Khan

Reputation: 2415

Swift

button.backgroundColor = UIColor.clear

objective-C

button.backgroundColor = [UIColor clearColor];

Upvotes: 0

eyesplice17
eyesplice17

Reputation: 231

Use UIColor.clear to make a color transparent.

It is very confusing that Apple calls it "default" instead of "clear."

Upvotes: 6

user7014451
user7014451

Reputation:

In the comments I found that:

  • Both buttons are created in InterfaceBuilder (IB).
  • The background color of each button is either set to default or something else in IB.
  • The idea is to have the second button have a transparent background color and a white title when the first is highlighted.

(I'll edit the above as needed. Among the things I'm not entirely sure about is what should happen after when the first button is no longer highlighted.)

If the above is the situation, you need to do the following:

  • Have the first button do things when either UIControlEventTouchDown or UIControlEventTouchDragEnter happen.
  • Have the first button then change the background color of the second through code.

Probably the easiest way to do this is not through IB, but instead through code. After adding your buttons in IB, create IBOutlets for both of them. Then you can do this:

@IBOutlet weak var firstButton: UIButton!
@IBOutlet weak var secondButton: UIButton!

override func viewDidLoad() {
    super.viewDidLoad()
    firstButton.addTarget(self, action: #selector(highlightSecondButton), for: .touchDown)
    firstButton.addTarget(self, action: #selector(highlightSecondButton), for: .touchDragEnter)
}

func highlightSecondButton(_ sender:UIButton) {
    secondButton.setTitleColor(UIColor.white, for: UIControlState.normal)
    secondButton.backgroundColor = nil
}

Upvotes: 8

Related Questions