gpt4 book ai didi

SwiftUI 分段控制 View 刷新时选定的分段文本动画

转载 作者:行者123 更新时间:2023-12-03 16:36:03 24 4
gpt4 key购买 nike

在更改 View 中的一些其他数据后刷新 View 时,我正在经历以下选定分段控件段中的文本动画:

segmented control text animation

这是错误/功能还是有办法消除这种行为?

这是重现效果的代码:

import SwiftUI

struct ContentView: View {
let colorNames1 = ["Red", "Green", "Blue"]
@State private var color1 = 0

let colorNames2 = ["Yellow", "Purple", "Orange"]
@State private var color2 = 0

var body: some View {
VStack {
VStack {
Picker(selection: $color1, label: Text("Color")) {
ForEach(0..<3, id: \.self) { index in
Text(self.colorNames1[index]).tag(index)
}
}.pickerStyle(SegmentedPickerStyle())

Text("Color 1: \(color1)")
}
.padding()

VStack {
Picker(selection: $color2, label: Text("Color")) {
ForEach(0..<3, id: \.self) { index in
Text(self.colorNames2[index]).tag(index)
}
}.pickerStyle(SegmentedPickerStyle())

Text("Color 2: \(color2)")
}
.padding()
}
}
}

这是在 iOS 13.4 / Xcode 11.4 下运行的

最佳答案

重新排列您的代码库...(这有助于 SwiftUI 仅“刷新”必要的 View )

import SwiftUI

struct ContentView: View {
let colorNames1 = ["Red", "Green", "Blue"]
@State private var color1 = 0

let colorNames2 = ["Yellow", "Purple", "Orange"]
@State private var color2 = 0

var body: some View {
VStack {
MyPicker(colorNames: colorNames1, color: $color1)
.padding()

MyPicker(colorNames: colorNames2, color: $color2)
.padding()
}
}
}

struct MyPicker: View {
let colorNames: [String]
@Binding var color: Int
var body: some View {
VStack {
Picker(selection: $color, label: Text("Color")) {
ForEach(0..<colorNames.count) { index in
Text(self.colorNames[index]).tag(index)
}
}.pickerStyle(SegmentedPickerStyle())

Text("Color 1: \(color)")
}
}
}

struct ContetView_Preview: PreviewProvider {
static var previews: some View {
ContentView()
}
}

结果

enter image description here

关于SwiftUI 分段控制 View 刷新时选定的分段文本动画,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60912170/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com