LoginSignup
4
5

More than 3 years have passed since last update.

SwiftUIでNavigationViewの背景をColorで設定したい

Last updated at Posted at 2019-11-21

困った点

swiftUIでNavigationViewの背景色を変えたいと思って
.backgroundとかでいじってみても反応してくれなくて、ボエェェってなったので解決方法を書いておきます

解決方法

NavigationView内でZStackを使う
これで解決できました。

イメージとしては
ZStackを使って
・カラーレイヤー
・UIパーツレイヤー
を重ねてやればいいっぽい。

まだNavigationViewのAPIが完成していないっていうことなのか、仕様なのか?

ちなみにUIColorでは無く、Colorで色を指定しているので注意


import SwiftUI

struct Welcome_view: View {
    var body: some View {
        NavigationView {
            ZStack {
                self.backGroundColor().edgesIgnoringSafeArea(.all)
                VStack (spacing: 80){
                    Text("welcome to pomboo!")
                        .font(.title)
                        .foregroundColor(Color.white)

                    VStack (spacing: 10) {
                        NavigationLink(destination: Login_view()) {
                            Text("Login")
                                .font(.headline)
                            .frame(width: 200.0, height: 50)
                            .background(/*@START_MENU_TOKEN@*/Color.white/*@END_MENU_TOKEN@*/)
                            .cornerRadius(20.0)
                            .shadow(radius: 20)
                        }

                        Text("or")
                            .foregroundColor(Color.white)

                        NavigationLink(destination: SignUp_view()) {
                            Text("Sign Up")
                                .font(.headline)
                                .foregroundColor(Color.white)
                            .frame(width: 200.0, height: 50)
                            .cornerRadius(20.0)
                            .overlay(
                                RoundedRectangle(cornerRadius: 20)
                                    .stroke(Color.white, lineWidth: 2)
                            )
                        }
                    }
                }
            }
        }
    }

    private func backGroundColor() -> LinearGradient {
        let start = UnitPoint.init(x: 0.0, y: 0.0)
        let end = UnitPoint.init(x: 1.0, y: 1.0)

        // convert UIColor to Color
        let colors = Gradient(colors: [Color.blue, Color(UIColor.blue)])
        let gradientColor = LinearGradient(gradient: colors, startPoint: start, endPoint: end)

        return gradientColor
    }
}

struct Welcome_view_Previews: PreviewProvider {
    static var previews: some View {
        Welcome_view()
    }
}

感想

swiftUIとっても便利なんですけど
どうもネストが深くなりがちで。。。

なんか良い方法無いかな?

4
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
5