Если представление не будет обновляться, я предполагаю, что его модификатор представления также не будет вызываться. Но «примитивные представления», такие как «Текст», всегда вызывают модификатор представления, несмотря на одну и ту же зависимость (строковый литерал). С другой стороны, пользовательское представление, которое оборачивает текстовое представление, не вызывает модификатор его представления.
Итак, вопрос, основанный на фрагменте кода:
- Почему цвет фона текста struct Test меняется, но не другие?
- Не следует ли создавать `Text(string:)` еще раз?
- Было бы лучше обернуть их, чтобы свести к минимуму повторение представлений? (Лично я так не думаю, потому что они дешевы. Не похоже, что их структурный вид меняется. Как вы это видите?)
func randomBackgroundColor() -> some View {
self.background {
Color(cgColor: .init(
red: .random(in: 0...1.0),
green: .random(in: 0...1.0),
blue: .random(in: 0...1.0),
alpha: 1))
}
}
}
struct A: View {
var body: some View {
Text("ASD")
.padding()
.randomBackgroundColor() // does not hcange color. Correct since view "A" does not have any dependency
}
}
struct B: View {
@Binding var num: Int
var body: some View {
HStack {
Text("\(num)")
.padding()
.randomBackgroundColor() // color changes. Correct since its dependency changes
C(fixed: "Fixed Text")
.randomBackgroundColor() // does not change color. Correct since the text remains the same
}
}
}
struct C: View {
let fixed: String
var body: some View {
Text(fixed)
.padding()
.randomBackgroundColor() // does not change color. Correct since the text remains the same
}
}
@Observable class MyVM {
var num = 1
}
struct Test: View {
@State private var vm = MyVM()
var body: some View {
Button("Randomize") {
vm.num = Int.random(in: 0...1000)
}
Text("ASD")
.randomBackgroundColor() // changes color whenever vm's num changes. Why?
A()
B(num: $vm.num)
C(fixed: "Fixed value") // does not change color despite new vm's num changes
.randomBackgroundColor()
.randomBackgroundColor()
}
}
Подробнее здесь: https://stackoverflow.com/questions/798 ... s-its-body
Мобильная версия