NSButton swift 自定义单选按钮
时间: 2024-04-11 08:33:27 浏览: 124
在 Swift 中,你可以使用 NSButton 来创建自定义的单选按钮。下面是一个简单的示例代码,演示如何创建一个自定义的单选按钮:
```swift
import Cocoa
class ViewController: NSViewController {
var radioButton1: NSButton!
var radioButton2: NSButton!
override func viewDidLoad() {
super.viewDidLoad()
// 创建第一个单选按钮
radioButton1 = NSButton(frame: NSRect(x: 50, y: 100, width: 100, height: 30))
radioButton1.title = "选项1"
radioButton1.setButtonType(.radio)
radioButton1.target = self
radioButton1.action = #selector(radioButtonClicked(_:))
self.view.addSubview(radioButton1)
// 创建第二个单选按钮
radioButton2 = NSButton(frame: NSRect(x: 50, y: 150, width: 100, height: 30))
radioButton2.title = "选项2"
radioButton2.setButtonType(.radio)
radioButton2.target = self
radioButton2.action = #selector(radioButtonClicked(_:))
self.view.addSubview(radioButton2)
}
@objc func radioButtonClicked(_ sender: NSButton) {
// 处理单选按钮的点击事件
if sender == radioButton1 {
print("选项1被选中")
} else if sender == radioButton2 {
print("选项2被选中")
}
}
}
```
这个示例代码创建了两个单选按钮,并为每个按钮设置了相应的标题、按钮类型、目标和动作。当用户点击单选按钮时,`radioButtonClicked` 方法会被调用,你可以在这个方法中处理按钮的点击事件。
希望这个示例对你有所帮助!
阅读全文
相关推荐














