面试题答案
一键面试import SwiftUI
struct ContentView: View {
@State private var rectangleWidth: CGFloat = 100
var body: some View {
VStack {
Rectangle()
.frame(width: rectangleWidth, height: 100)
.foregroundColor(.blue)
Button("Animate") {
withAnimation(.linear(duration: 3)) {
rectangleWidth = 200
}
}
}
}
}
上述代码实现了在SwiftUI中,当点击按钮时,矩形视图的宽度在3秒内从100逐渐变化到200。@State
用于追踪 rectangleWidth
的状态变化,Button
点击时,withAnimation
闭包中的代码会以线性动画,时长3秒的方式更新 rectangleWidth
,从而使矩形的宽度发生动画变化。