我开始尝试SwiftUI,我很惊讶,它似乎不是简单的改变一个视图的背景颜色。你如何使用SwiftUI做到这一点?
当前回答
你可以这样做:
.background(Color.black)
围绕着你的视野。
如。从默认模板(我把它包围在一个组):
var body: some View {
VStack {
Text("Hello SwiftUI!")
}
.background(Color.black)
}
为了添加一些不透明度,你也可以添加.opacity方法:
.background(Color.black.opacity(0.5))
你也可以通过CMD +单击视图,然后单击Show SwiftUI Inspector > Background > Your Color来使用视图的inspect元素
其他回答
这个解决方案有效吗?:
添加以下行到SceneDelegate: window.rootViewController?backgroundColor = .black
func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
if let windowScene = scene as? UIWindowScene {
window.rootViewController?.view.backgroundColor = .black
}
NavigationView例子:
var body: some View {
var body: some View {
NavigationView {
ZStack {
// Background
Color.blue.edgesIgnoringSafeArea(.all)
content
}
//.navigationTitle(Constants.navigationTitle)
//.navigationBarItems(leading: cancelButton, trailing: doneButton)
//.navigationViewStyle(StackNavigationViewStyle())
}
}
}
var content: some View {
// your content here; List, VStack etc - whatever you want
VStack {
Text("Hello World")
}
}
我喜欢声明一个修饰符来改变视图的背景颜色。
extension View {
func background(with color: Color) -> some View {
background(GeometryReader { geometry in
Rectangle().path(in: geometry.frame(in: .local)).foregroundColor(color)
})
}
}
然后我通过将颜色传递给视图来使用修饰符。
struct Content: View {
var body: some View {
Text("Foreground Label").foregroundColor(.green).background(with: .black)
}
}
要制作一个中央/可重用的后台小部件,您可以这样做-
import SwiftUI
struct BgView<Content>: View where Content: View {
private let content: Content
public init(@ViewBuilder content: () -> Content) {
self.content = content()
}
var body : some View {
ZStack {
Color.black.ignoresSafeArea()
content
}
}
}
并且可以像下面这样轻松地在所有视图中使用-
import SwiftUI
struct TestView: View {
var body: some View {
BgView{
Text("Hello, World!")
}.foregroundColor(.white)
}
}
struct TestView_Previews: PreviewProvider {
static var previews: some View {
TestView()
}
}
首先,你应该使用
ZStack {
Color("Desired_color_name").ignoresSafeArea()
// if you create any color set then give that colour set name
// otherwise use Color.gray or as you want the colour name
//Here you should start your design
}
推荐文章
- 如何删除默认的导航栏空间在SwiftUI导航视图
- 在c#代码中设置WPF文本框的背景颜色
- Android:为什么视图没有maxHeight ?
- 在android中从上下文获取活动
- CSS:背景图像上的背景色
- 如何在Swift中删除视图的所有子视图?
- SwiftUI中的活动指标
- 如何使div背景颜色透明的CSS
- 如何用SwiftUI调整图像大小?
- 我能在视图中得到当前控制器的名称吗?
- 在SwiftUI中创建一个VStack填充屏幕宽度
- CSS:设置背景色为窗口宽度的50%
- 如何设置不透明度(Alpha)的视图在Android
- 我如何改变一个视图的背景颜色?
- 是否有一种方法以编程方式滚动滚动视图到特定的编辑文本?