使用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())
发布于 2020-05-16 08:37:02
这是默认的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) {
}
}
发布于 2022-04-12 21:43:10
...For examle,图像中的选择器对于文本具有不同的宽度。
如果你到这里来找iOS SwiftUI SegmentedPickerStyle解决方案.我发现iOS SwiftUI .pickerStyle(SegmentedPickerStyle())
将符合全局UISegmentedControl.appearance()
设置,因此我使用以下方法成功地分配了每个段的宽度:
UISegmentedControl.appearance().apportionsSegmentWidthsByContent = true
例如,如果您希望在应用程序中支持动态类型字体,这尤其有用,否则会导致长名称的段被吹掉并被截断。aside: I also use this trick to change the SwiftUI segmented picker's font size! see [https://stackoverflow.com/a/71834578/3936065]
发布于 2022-04-07 20:49:35
啊,到了AppKit方法。
确实很聪明。不过,这对我没有用,蒙特莱12.3
使用Xcode的Visual进一步调试,我可以在视图层次结构中看到NSPickerConfigurator类,但没有看到NSSegmetedControl。
苹果似乎正在从等级体系中清除NSViews。
是时候去思考纯粹的迅捷了。
https://stackoverflow.com/questions/61833013
复制相似问题