swift - 使用 SegmentedPickerStyle 为 SwiftUI Picker 设置段等宽
问题描述
使用SegmentedPickerStyle
样式Picker
可以使控件看起来像UISegmentedControl
. 但我想知道如何调整选择器中的段宽度。例如,图像中的选择器具有不同的文本宽度。
有没有办法让 SwiftUI 中的段具有相同的宽度?
Picker(selection: $store.utility.saliencyType, label: EmptyView()) {
ForEach(Store.Utility.SaliencyType.allCases, id: \.self) { saliencyType in
Text(saliencyType.text)
.tag(saliencyType)
}
}.pickerStyle(SegmentedPickerStyle())
解决方案
这是默认的 macOS NSSegmetedControl 行为
@property NSSegmentDistribution segmentDistribution API_AVAILABLE(macos(10.13));
// Defaults to NSSegmentDistributionFill on 10.13, older systems will continue to behave similarly to NSSegmentDistributionFit
更新:这是基于NSSegmentedControl
在运行时视图层次结构中查找的解决方法。
免责声明:实际上它是安全的,即。运行时没有崩溃,但可以在将来返回默认行为时停止工作。
因此,想法是NSView
通过可表示注入到 (!!) 上方的视图层次结构Picker
中,如
Picker(selection: $store.utility.saliencyType, label: EmptyView()) {
ForEach(Store.Utility.SaliencyType.allCases, id: \.self) { saliencyType in
Text(saliencyType.text)
.tag(saliencyType)
}
}
.overlay(NSPickerConfigurator { // << here !!
$0.segmentDistribution = .fillEqually // change style !!
})
.pickerStyle(SegmentedPickerStyle())
和配置器本身
struct NSPickerConfigurator: NSViewRepresentable {
var configure: (NSSegmentedControl) -> Void
func makeNSView(context: Context) -> NSView {
let view = NSView()
DispatchQueue.main.async {
if let holder = view.superview?.superview {
let subviews = holder.subviews
if let nsSegmented = subviews.first?.subviews.first as? NSSegmentedControl {
self.configure(nsSegmented)
}
}
}
return view
}
func updateNSView(_ nsView: NSView, context: Context) {
}
}
推荐阅读
- java - 如何使用 Java 获取在 TextInput/OutputFormat 中创建的配置单元表的架构
- html - 不能只用 AngularJS 代码添加单个数字
- javascript - 问题导入/需要pondjs
- wordpress - 找不到 wordpress 版本或更新
- r - ggplot将颜色代码列与R数据框中的另一列匹配
- clion - 如何防止 CLion 调试成 C++ 源文件
- c# - Windows 窗体,SendMessage 行中的语法错误
- sql-server - 自动在不同文件组中创建索引,编辑发布配置文件脚本
- facebook - 从我的 Facebook 页面获取公共照片来源
- python - 为什么 timeit() 函数在传递函数和字符串表达式时返回不同的结果?