简体   繁体   中英

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?

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
}

Use UIColor.clear to make a color transparent.

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

Swift

button.backgroundColor = UIColor.clear

objective-C

button.backgroundColor = [UIColor clearColor];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM