如何解决SwiftUI 条件 .frame 视图修饰符
我的代码如下:
Rectangle()
.fill(Color.red)
.frame(width: 60,height: 60,alignment: .center)
.cornerRadius(recording ? 5 : 30)
所以我想知道 .frame
是否可以像 .cornerRadius
一样是有条件的。我这样做是为了变形形状,但是我还需要在变形时使其变小。一个例子是语音备忘录应用的录音按钮。
解决方法
是的,您也可以将三元条件语句与 .frame 结合使用。
示例:
.frame(width: recording ? 40 : 60,height: recording ? 40 : 60,alignment: .center)
如果您正在谈论完全不使用框架修饰符(或提供一种干净的方式来处理不同的框架),ViewModifier
可能是一个不错的选择:
struct ContentView: View {
@State private var recording = false
var body: some View {
Rectangle()
.fill(Color.red)
.modifier(CustomFrameModifier(active: recording))
.cornerRadius(recording ? 5 : 30)
}
}
struct CustomFrameModifier : ViewModifier {
var active : Bool
@ViewBuilder func body(content: Content) -> some View {
if active {
content.frame(width: 60,height: 60,alignment: .center)
} else {
content
}
}
}
,
我想你想要这样的东西
Rectangle()
.fill(Color.red)
.frame(width: recording ? 45 : 60,height: recording ? 30 : 60,alignment: .center)
.cornerRadius(recording ? 5 : 30)
.onTapGesture {
recording.toggle()
}
.animation(.default,value: recording)
,
你可以用 ?
import SwiftUI
struct ContentView: View {
@State private var recording: Bool = Bool()
@State private var color: Color = Color.blue
var body: some View {
ZStack {
Circle()
.fill(Color.white)
.frame(width: 60.0,height: 60.0,alignment: .center)
.shadow(radius: 10.0)
Circle()
.fill(color)
.frame(width: recording ? 30.0 : 60.0,height: recording ? 30.0 : 60.0,alignment: .center) // <<: Here!
}
.onTapGesture { recording.toggle() }
.animation(.easeInOut,value: recording)
.onChange(of: recording) { newValue in if newValue { colorFunction() } else { color = Color.blue } }
}
func colorFunction() {
if (color != Color.red) { color = Color.red } else { color = Color.clear }
DispatchQueue.main.asyncAfter(deadline: .now() + .seconds(1)) { if recording { colorFunction() } }
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。