Skip to content

Commit f46e952

Browse files
committed
Fix Button actions and fg color on tvOS
Button actions weren't working at all on tvOS because UIControl.Event.touchUpInside doesn't get triggered on tvOS. Instead button interactions trigger UIControl.Event.primaryActionTriggered. tvOS buttons also have some weird foreground color stuff, see comments I left in the code.
1 parent 8c6bf77 commit f46e952

File tree

1 file changed

+25
-6
lines changed

1 file changed

+25
-6
lines changed

Sources/UIKitBackend/UIKitBackend+Control.swift

Lines changed: 25 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -18,13 +18,16 @@ internal final class ButtonWidget: WrapperWidget<UIButton> {
1818

1919
init() {
2020
let type: UIButton.ButtonType
21+
let event: UIControl.Event
2122
#if os(tvOS)
2223
type = .system
24+
event = .primaryActionTriggered
2325
#else
2426
type = .custom
27+
event = .touchUpInside
2528
#endif
2629
super.init(child: UIButton(type: type))
27-
child.addTarget(self, action: #selector(buttonTapped), for: .touchUpInside)
30+
child.addTarget(self, action: #selector(buttonTapped), for: event)
2831
}
2932
}
3033

@@ -221,11 +224,27 @@ extension UIKitBackend {
221224
environment: EnvironmentValues
222225
) {
223226
let buttonWidget = button as! ButtonWidget
224-
buttonWidget.child.setAttributedTitle(
225-
UIKitBackend.attributedString(
226-
text: label, environment: environment, defaultForegroundColor: .link),
227-
for: .normal
228-
)
227+
228+
// tvOS's buttons change foreground color when focused. If we set an
229+
// attributed string for `.normal` we also have to set another for
230+
// `.focused` with a colour that's readable on a white background.
231+
// However, with that approach the label's color animates too slowly
232+
// and all round looks quite sloppy. Therefore, it's safest to just
233+
// ignore foreground color for buttons on tvOS until we have a better
234+
// solution.
235+
#if os(tvOS)
236+
buttonWidget.child.setTitle(label, for: .normal)
237+
#else
238+
buttonWidget.child.setAttributedTitle(
239+
UIKitBackend.attributedString(
240+
text: label,
241+
environment: environment,
242+
defaultForegroundColor: .link
243+
),
244+
for: .normal
245+
)
246+
#endif
247+
229248
buttonWidget.onTap = action
230249
}
231250

0 commit comments

Comments
 (0)