Skip to content

Instantly share code, notes, and snippets.

@sebjvidal
Created November 5, 2024 15:35
Show Gist options
  • Save sebjvidal/e801786aec3bae36642fde8909009ca0 to your computer and use it in GitHub Desktop.
Save sebjvidal/e801786aec3bae36642fde8909009ca0 to your computer and use it in GitHub Desktop.
UIButton Control Size for Mac Catalyst
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