naljin
naljin

Reputation: 611

Change other view's background color by button state

I want to change other view's background color by UIButton state (e.g. When button is highlighted, change background color of myView, not the button's background color). And my button is connected as @IBOulet UIButton. I don't want to make another customButton class that inherits UIButton to use isHighlighted property. In this case, what should I do?

Upvotes: 0

Views: 500

Answers (1)

Pancho
Pancho

Reputation: 4143

You can use Swift's new framework called Combine to subscribe and listen to changes of this property. You will also need to import Combine.

Here is an example

import Combine
import UIKit

@IBOutlet weak var button: UIButton!
var subscriptions = Set<AnyCancellable>()

override func viewDidLoad() {
    super.viewDidLoad()
    button
       .publisher(for: \.isHighlighted)
       .sink { highlighted in
          if highlighted {
             // do whatever you need here
          } 
       }
       .store(in: &subscriptions)
}

Here is the full documentation from Apple if you want to use Combine

Upvotes: 2

Related Questions