Created
November 5, 2024 15:35
-
-
Save sebjvidal/e801786aec3bae36642fde8909009ca0 to your computer and use it in GitHub Desktop.
UIButton Control Size for Mac Catalyst
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import UIKit | |
class ViewController: UIViewController { | |
override func viewDidLoad() { | |
super.viewDidLoad() | |
let button = UIButton(type: .system) | |
button.role = .primary | |
button.controlSize = .large | |
button.setTitle("Button", for: .normal) | |
button.translatesAutoresizingMaskIntoConstraints = false | |
view.addSubview(button) | |
NSLayoutConstraint.activate([ | |
button.centerXAnchor.constraint(equalTo: view.centerXAnchor), | |
button.centerYAnchor.constraint(equalTo: view.centerYAnchor), | |
button.widthAnchor.constraint(equalToConstant: 200) | |
]) | |
} | |
} | |
extension UIButton { | |
var nsButton: NSObject? { | |
let buttonMacVisualElement = subviews.first { view in | |
return String(describing: type(of: view)) == "UIButtonMacVisualElement" | |
} | |
let uiNSView = buttonMacVisualElement?.subviews.first { view in | |
return String(describing: type(of: view)) == "_UINSView" | |
} | |
return uiNSView?.value(forKey: "contentNSView") as? NSObject | |
} | |
var controlSize: ControlSize { | |
get { | |
let rawValue = nsButton?.value(forKey: "controlSize") as? Int | |
let controlSize = ControlSize(rawValue: rawValue ?? 0) ?? .regular | |
return controlSize | |
} set { | |
nsButton?.setValue(newValue.rawValue, forKey: "controlSize") | |
} | |
} | |
enum ControlSize: Int { | |
case regular = 0 | |
case small = 1 | |
case mini = 2 | |
case large = 3 | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment