5

I have a sign in apple button. It has style .black in light mode:

let button = ASAuthorizationAppleIDButton(type: .signIn, style: .black)

I want it to have style .white in dark mode

Accessing the style to change it does not seem possible like this:

button.style = .white

Does someone know if this is possible in a clean way? Without having to recreate a button when the

traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {

detects a mode change?

regina_fallangi
  • 2,080
  • 2
  • 18
  • 38
  • 2
    It seems that you would need to create a new instance of the button. Depending on your UI, the white outline style may work in both light and dark – Paulw11 May 27 '20 at 23:43

1 Answers1

1

As far as I have found out, it is not possible to change the style of a ASAuthorizationAppleIDButton once it has been instantiated. The final solution has been instantiating two buttons on initialisation and only showing the needed one according to the current traitCollection. There are other solutions, but this one makes sure only two instances are needed altogether.

The two buttons are saved inside a stack view:

let blackButton = ASAuthorizationAppleIDButton(type: .signIn, style: .black)
let whiteButton = ASAuthorizationAppleIDButton(type: .signIn, style: .black)

private lazy var stackView = {
    let stackView = UIStackView(arrangedSubviews: [blackButton, whiteButton])
    stackView.axis = .vertical
    return stackView
}()

One can position the stackView there where one would position the regular button in the UI.

One would listen to trait collection changes and hide/show the desired button:

override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
        super.traitCollectionDidChange(previousTraitCollection)
        let currentInterface = UITraitCollection.current
        // Only do a change when the style interface really changed
        guard previousTraitCollection?.userInterfaceStyle != currentInterface.userInterfaceStyle else {
            return
        }

        // Hide or show buttons depending on your design.
        if currentInterface.userInterfaceStyle == .dark {
            blackButton.isHidden = true
            whiteButton.isHidden = false
        } else {
            blackButton.isHidden = false
            whiteButton.isHidden = true
        }
    }
regina_fallangi
  • 2,080
  • 2
  • 18
  • 38