LoginSignup
2
2

More than 3 years have passed since last update.

[SwiftUI]NavigationViewのnavigationBarTitle位置に画像とテキストを両方入れる方法

Posted at

実装するもの

SwiftUIにおけるSwiftUI NavigationViewでListからNavigationLinkで遷移する方法ではnavigationBarTitleの使い方についても触れましたが、ここでは以下の実装をする為に必要な方法をご紹介したいと思います。

スクリーンショット 2020-09-06 22.08.11.jpg

Code

ContentView
struct ContentView: View {

    var body: some View {

            VStack {
                TitleView(image: Image("SwiftUI"),titleName: "SwiftUI")
                    .frame(width: UIScreen.main.bounds.width * 0.95, height: UIScreen.main.bounds.height * 0.1)                  
                List(1..<100) { num in
                    NavigationLink(destination: Text("Lesson\(num)")) {
                    Text("Lesson\(num)")
                    }
                }      
        }
    }
}

これに加えて
Cmd+Nで新規TitleViewを作成し
スクリーンショット 2020-09-06 22.10.39.jpg

スクリーンショット 2020-09-06 22.10.59.jpg
以下のCodeを追加します。

Code

TitleView
struct TitleView: View {
    let image: Image
    let titleName: String

    var body: some View {
        HStack {
            VStack(alignment: .leading) {
                image
                    .resizable()
                    .frame(width: 50, height: 50)

        }
            ZStack {
                Text("\(titleName)")
                    .fontWeight(.black)
                    .foregroundColor(Color.black)
                    .font(.largeTitle)
            }
            Spacer()
        }
        .padding()
        .background(Color.white)
        .clipShape(RoundedRectangle(cornerRadius: 10))
    }
}

解説

現段階でnavigationBarTitleにImageとTextを入れる方法がない(と思う)為、TitleViewを作り、最上部にVstackで配置する事でそれらしく見せる事ができます。また.frame(width: UIScreen.main.bounds.width * 0.95, height: UIScreen.main.bounds.height * 0.1)では高さや幅をデバイスのサイズによって変更する為、綺麗な設計をする上では非常に有効ですので是非ご活用ください。
また使用するImageはassetにあらかじめご用意ください。

スクリーンショット 2020-09-06 22.14.48.jpg

最後に

普段は個人でSwiftUIでアプリを作っています。ハードも作るの大好きです。
よければ下記もチェックして下さい♪
Twitter
https://twitter.com/oka_yuuji
note
https://note.com/oka_yuuji

2
2
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
2
2