Ary*_*n C 6 swift swiftui xcode12
我正在 SwiftUI 的表单中创建一个选择器。在选择器中选择新元素时,当视图拉回表单时,选择器行不会被取消选择。这是我的意思的屏幕截图,选择器行像这样保持灰色。
我读了一些以前的答案,说这是 Xcode 11.3 中的一个错误,但是,我正在运行 Xcode 12 beta 4 并且不确定这是否仍然是一个错误。
这就是我创建选择器的方式:
struct SettingsView: View {
@State private var currentSelection = 1
var body: some View {
NavigationView {
Form {
Section {
Picker("Test 2", selection: $currentSelection) {
ForEach(1 ...< 100) { i in
Text(String(i)).tag(i)
}
}
}
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
这是我的 ContentView,我从中展示了 SettingsView:
enum ActiveSheet: Identifiable {
case photoPicker, settings
var id: Int {
self.hashValue
}
}
struct ContentView: View {
@State var activeSheet: ActiveSheet?
var body: some View {
NavigationView {
VStack {
Text("Hello world")
Button("Select Photo") {
self.activeSheet = .photoPicker
}
}
.navigationBarTitle(Text("Title"), displayMode: .inline)
.navigationBarItems(trailing: Button(action: {
self.activeSheet = .settings
}, label: {
Image(systemName: "gear")
.imageScale(.large)
}))
}
.sheet(item: $activeSheet) { item in
if item == .photoPicker {
ImagePicker(selectedImage: $image, sourceType: .photoLibrary)
} else {
SettingsView()
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
编辑:我创建了一个全新的项目,这是唯一的代码:
import SwiftUI
struct ContentView: View {
@State private var currentSelection = 0
var body: some View {
NavigationView {
Form {
Section {
Picker("Test Picker", selection: $currentSelection) {
ForEach(0 ..< 100) { i in
Text(String(i)).tag(i)
}
}
}
}.navigationBarTitle(Text("Test"))
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
Run Code Online (Sandbox Code Playgroud)
问题仍然存在。
(根据记录,我在 Big Sur、Xcode 12.2 上,这个问题仍然存在。)
经过几次测试后,发现此行为是由于同一视图内有多个列表造成的。您可以看到,当导航堆栈弹出回视图时,第一个“列表”(即 UITableView)会取消选择其选定的行,但这对于第一个列表之后的列表不起作用。很明显这是一个错误(在 SwiftUI 中?!)。
我发现规避此错误的唯一方法(某种程度上是蹩脚的方法)是让Introspect 库获取感兴趣的 tableView(在本例中是显示表单的 tableView)并执行一些类似这样的内务处理:
import Introspect
...
public class Weak<T: AnyObject> {
public weak var value: T?
public init(_ value: T? = nil) {
self.value = value
}
}
private var listTableView = Weak<UITableView>()
var body: Some View {
NavigationView {
VStack {
List {
...
}
Form {
Picker(...) {
...
}
}
.introspectTableView { listTableView.value = $0 }
.onAppear() {
if let tableView = listTableView.value, let indexPath = tableView.indexPathForSelectedRow {
tableView.deselectRow(at: indexPath, animated: true)
}
}
}
Run Code Online (Sandbox Code Playgroud)
它有效......但没有动画(有人吗?)。
| 归档时间: |
|
| 查看次数: |
504 次 |
| 最近记录: |