Devlog
article thumbnail

위 글은 유튜브 정대리님의 SwiftUI fundamental Tutorial 강좌를 보고 작성한 정리글로

자세한 내용은 유튜브를 통해 확인하시길 권장합니다.

 

 

 

import SwiftUI

struct MyNavigationView: View{
    var body: some View{
        
        NavigationView{
        Text("MyNavigationView")
            .navigationTitle("안녕하세요")
        }
    }
}

.navigationTitle(): 좌측 상단에 들어옴

default=LargeTitle

 

 

 

 

 

import SwiftUI

struct MyNavigationView: View{
    var body: some View{
        
        NavigationView{
        Text("MyNavigationView")
            .navigationBarTitle("안녕하세요", displayMode: .automatic/inline/large)
        }
    }
}

displayMode: .automatic / .inline / .large

 

 

 

 

 

앞 시간에 만든 List에 displayMode 적용

import SwiftUI

struct MyNavigationView: View{
    var body: some View{
        
        NavigationView{
        
            MyList()
            .navigationBarTitle("안녕하세요", displayMode: .inline)
   
        }
    }
}

 

displayMode: .inline / .large 적용한 모습

 

 

displayMode의 automatic과 large는 거의 동일하게 봐도 무방

large와 automatic 상태에서 스크롤을 할때 자동으로 inline 처리가 됨

 

 

 

 

 

.navigationBarItems(): 상단 좌, 우에 아이템을 놓을 수 있음 (텍스트, 버튼 등등)

import SwiftUI

struct MyNavigationView: View{
    var body: some View{
        
        NavigationView{
        
            MyList()
           
                .navigationBarTitle("안녕하세요")
                .navigationBarItems(leading: Text("test"))

            
            
        }
    }
}

좌측 상단에 아이템 출력

 

 

import SwiftUI

struct MyNavigationView: View{
    var body: some View{
        
        NavigationView{
            MyList()
            
                .navigationBarTitle("안녕하세요")
                .navigationBarItems(leading: Button(action:{
                	print("클릭 됨")
                }){
                    Text("test")
                })
        }
    }
}

강의 보면 디버그 프리뷰할 때 디버깅 창에 print 된 값이 뜨는데 난 왜 안뜨지

코드에 문제가 있는게 아니라 설정에 문제가 있는 것 같음 시뮬레이터 돌릴 때는 디버깅 창에 출력 잘 됨 ㅠ

 

 

 

 

 

우측 상단에 navigationBarItems(NavigationLink) 놓기

import SwiftUI

struct MyNavigationView: View{
    var body: some View{
        
        NavigationView{
        
            MyList()
           
//                .navigationBarTitle("안녕하세요")
                .navigationBarItems(leading: Button(action:{
                    print("클릭 됨")
                }){
                    Text("test")
                }, trailing: NavigationLink(
                    destination: Text("NextPage")){
                        Text("Navigate")
                    })
        }
    }
}

leading 뒤에 콤마 찍고 trailing 설정하면 됨

 

NextPage로 넘어가면 좌측 상단에 MY LIST라 표시가 됨

 

 

 

 

❓참고할 점

기존에 만들어 둔 MyList navigationBarTitle을 MY LIST라 설정해서 그런지 navigationBarTitle("안녕하세요")가 먹히지 않음

 

 

 

 

버튼을 꾸며주는 부분에는 sf Symbol 같이 이미지를 사용할 수 있음

import SwiftUI

struct MyNavigationView: View{
    var body: some View{
        
        NavigationView{
        
            MyList()
           
//                .navigationBarTitle("안녕하세요")
                .navigationBarItems(leading: Button(action:{
                    print("클릭 됨")
                }){
                    Text("test")
                }, trailing: NavigationLink(
                    destination: Text("NextPage")){
                        
                        Image(systemName:  "bookmark.fill")
                            .font(.system(size: 25))
                            .foregroundColor(Color.black)
                    })
            
        }
    }
}

 

 

 

 

 

📌 응용하던 중 문제 발생

NavigationView를 만들 때는 잘 먹히던게

이게 ContentView랑 엮어지면서 리스트 상단이 내려가고 네비게이션 탭도 두개가 생겨버림 ㅠ 

왜요 WHY?

 

NavigationView로 ContentView를 시작하게 되었고

MyProfileView에서 또 NavigationView로 감싸주면 NavigationView가 중첩되어서 공간이 붕 뜨고 돌아가는 탭도 두 개가 뜨게 되는 것

 

그래서 한층으로 옮겨다니는 형태면 NavigationView로 감싸줄 필요가 없음

 

ContentView의 NavigationView로 MyProfileView로 넘어왔기 때문에 MyProfileView에서는 NavigationView로 감싸 줄 필요가 없음

 

 

 

 

 

 

응용하기(여태까지 배운 것들 엮어보기) 최종본

import SwiftUI

struct ContentView: View {
    
    @State //State는 값을 감지함
    var isNavigationBarHidden : Bool = false
    
    var body: some View {
        
        NavigationView{
            
            ZStack(alignment: .bottomTrailing){
                
                VStack(alignment: .leading, spacing: 0){
                    
                    HStack{
                        
                        NavigationLink(destination: MyList()){
                            Image(systemName: "line.horizontal.3")
                                .font(.largeTitle)
                                .foregroundColor(.black)
                            
                        }
                        
                        Spacer()
                        
                        NavigationLink(destination: MyProfile()){
                            Image(systemName: "person.crop.circle.fill")
                                .font(.largeTitle)
                                .foregroundColor(.black)
                            
                        }
                        
                        
                    }.padding(.top, 20)
                    .padding(.horizontal, 20)
                    
                    Text("TODO LIST")
                        .font(.system(size: 40))
                        .fontWeight(.black)
                        .padding(.horizontal, 20)
                        .padding(.top,20)
                    ScrollView{
                                VStack{
                                        MyCard()
                                    MyProject(icon: "tray.fill", title: "책상 정리하기", start: "13:00", end: "14:00", bgColor: Color.blue)
                                    MyProject(icon: "book.fill", title: "책 읽기", start: "14:00", end: "16:00", bgColor: Color.green)
                                    MyProject(icon: "case.fill", title: "기숙사 짐 싸기", start: "16:00", end: "18:00", bgColor: Color.red)
                                    MyBasic()
                                        
                                        
                                }.padding()
                        }
                }
                Circle()
                    .foregroundColor(Color.yellow)
                    .frame(width:60, height: 60)
                    .overlay(Image(systemName: "plus")
                                .font(.system(size:30))
                                .foregroundColor(.white))
                    .padding(10)
                    
                    .shadow(radius: 20)
            }//ZStack
            
            .navigationTitle("Main")
            .navigationBarHidden(self.isNavigationBarHidden)
            .onAppear{
                self.isNavigationBarHidden = true
                //렌더링되면서 self.isNavigationBarHidden이 true가 되면서 뷰를 다시 그림 - > 없어짐 근데 둘 다 없어짐 
            }
            
        }//NavigationView

    }
}
import SwiftUI

struct HideRowSeparatorModifier: ViewModifier {
    static let defaultListRowHeight: CGFloat = 44
    
    var insets: EdgeInsets
    var background: Color
    init(insets: EdgeInsets, background: Color){
        self.insets = insets
        
        var alpha: CGFloat = 0
        
        UIColor(background).getWhite(nil, alpha: &alpha)
        assert(alpha == 1, "")
        self.background = background
    }
    
    func body(content: Content) -> some View {
        content
            .padding(insets)
            .frame(
                minWidth: 0, maxWidth: .infinity, minHeight: Self.defaultListRowHeight,   alignment: .leading
            )
            .listRowInsets(EdgeInsets())
            .background(background)
    }
}
extension EdgeInsets{
    static let defaultListRowInsets = Self(top: 10, leading: 10, bottom: 10, trailing: 10)
}
extension View {
    func hideRowSeparator(insets: EdgeInsets = .defaultListRowInsets, background: Color = .white)
    -> some View {
        modifier(HideRowSeparatorModifier(insets: insets, background: background))
    }
}


struct MyList: View{
    
    
    var body: some View{
        
        List{
            
            Section(
                header:
                    Text("TODAY")
                    .font(.headline)
                    .foregroundColor(.black)
                ,footer:
                    Text("HAVE A NICE DAY 👍")
                ){
                ForEach(1...3, id: \.self){
                    itemIndex in //Text("MY LIST \(itemIndex)")
                    MyProject(icon: "book.fill", title: "책 읽기 \(itemIndex)", start: "13:00", end: "15:00", bgColor: Color.green).hideRowSeparator(insets: EdgeInsets(top: 10, leading: 10, bottom: 10, trailing: 10))
                }
            }
            .listRowInsets(EdgeInsets.init(top: 10, leading: 10, bottom: 10, trailing: 10))
            
            Section(
                header:
                    Text("TOMORROW")
                    .font(.headline)
                    .foregroundColor(.black)
                ,footer:
                    Text("GOOD DAY👍")
            ){
                ForEach(1...20, id: \.self){
                    itemIndex in //Text("MY LIST \(itemIndex)")
                    MyProject(icon: "book.fill", title: "책 읽기 \(itemIndex)", start: "13:00", end: "15:00", bgColor: Color.blue).hideRowSeparator(insets: EdgeInsets(top: 10, leading: 10, bottom: 10, trailing: 10),background: Color.yellow)
                }
            }
            .listRowInsets(EdgeInsets.init(top: 10, leading: 10, bottom: 10, trailing: 10))
        }
        .listStyle(GroupedListStyle())
        
        .navigationBarTitle("MY LIST")
        
        
        
    }
}
import SwiftUI

struct MyProfile: View {
    
    
    var body: some View {
        ScrollView{
            VStack{
                
                
                    CircleImageView()
                        .padding(.vertical, 20)
                        

                    .navigationBarTitle("MY PROFILE", displayMode: .automatic)
                        
                  
                    .navigationBarItems(trailing: NavigationLink(destination: MySetting()){
                        Image(systemName: "slider.horizontal.3")
                            .font(.system(size: 25))
                            .foregroundColor(.black)
                    })
                
                   
                
                
                Text("덩이")
                    .font(.system(size: 30))
                    .fontWeight(.bold)
                    .padding(.top, 30)
                Text("막학년 코딩노예")
                    .font(.system(size:20))
                    .padding(.top, 20)
                
                HStack{
                        NavigationLink(
                            destination: MyWebView(url: "https://www.instagram.com/__juzzg").edgesIgnoringSafeArea(.all)){
                            Text("팔로우 하기")
                                .font(.system(size: 20))
                                .fontWeight(.bold)
                                .foregroundColor(Color.white)
                                .padding(10)
                                .background(Color.purple)
                                .cornerRadius(20)
                        }
                        NavigationLink(
                            destination: MyWebView(url: "https:/blog.naver.com/hj__0403")
                                .edgesIgnoringSafeArea(.all)){
                            Text("서로이웃 하기")
                                .font(.system(size: 20))
                                .fontWeight(.bold)
                                .foregroundColor(Color.white)
                                .padding(10)
                                .background(Color.green)
                                .cornerRadius(20)
                    }
                    
                }//HStack
                
                .padding(15) //버튼패딩
                
            }
        }
    }
}
import SwiftUI
import WebKit

struct MyWebView: UIViewRepresentable {
    
    var url: String
    
    //UI View 만들기
    func makeUIView(context: Context) -> WKWebView {
        
        //url unwrapping
        guard let url = URL(string: self.url)
        else{ //url이 없으면 기본 웹페이지 보여줌
            return WKWebView()
        }
        
        //위에서 받은 url로 url 리퀘스트 인스턴스 생성
        let urlRequest = URLRequest(url: url)
        let wkWebview = WKWebView()
        wkWebview.load(urlRequest)
        return wkWebview
    }

    func updateUIView(_ uiView: WKWebView, context: UIViewRepresentableContext<MyWebView>)
        {
            
    }
}
import SwiftUI

struct CircleImageView : View{
    var body : some View{

        Image("profile")
 
            .resizable()
            
            .scaledToFill()

            .frame(width: 300, height: 300)
            
            .clipShape(Circle())
            .shadow(color: .gray, radius: 15)
            .overlay(
                Circle()
                    .foregroundColor(.yellow)
                    .opacity(0)
   
        )

            .edgesIgnoringSafeArea(.all)
    }
}
import SwiftUI
struct MySetting:View {
    var body: some View{
        Text("Setting Page")
    }
}
import SwiftUI

struct MyCard : View {
    
    @State
    var shouldShowAlert : Bool = false
    
    let date = Date()
    
    var body: some View{
       
        VStack(alignment: .leading, spacing: 0){
            
            Rectangle().frame(height:0)
            
            Text("iOS 프로젝트")
                .font(.system(size:23))
                .fontWeight(.bold)
                .padding(.bottom,5)
           
            Text(date, style: .time)
                .foregroundColor(.secondary)
            
            Spacer().frame(height:20)
            
            HStack{
                Image("1")
                    .resizable()
                    .frame(width: 50, height:50)
                    .clipShape(Circle())
                    .overlay(
                    Circle()
                        .stroke(lineWidth: 1)
                        .foregroundColor(Color.red))
                Image("2")
                    .resizable()
                    .frame(width: 50, height:50)
                    .clipShape(Circle())
                Image("3")
                    .resizable()
                    .frame(width: 50, height:50)
                    .clipShape(Circle())
                
                Spacer()
                
                Button(action:{
                    print("확인 되었습니다")
                    self.shouldShowAlert = true
                    
                }){
                    //버튼 생김새
                    Text("확인")
                        .fontWeight(.bold)
                        .foregroundColor(.white)
                        .padding()
                        .frame(width: 80)
                        .background(Color.blue)
                        .cornerRadius(20)
                }.alert(isPresented: $shouldShowAlert){
                    Alert(title: Text("완료 하셨나요?"))
                }
            }
        }
        .padding(30)
        .background(Color.yellow)
        .cornerRadius(20)
    }
}
import SwiftUI

struct MyBasic: View{
    
    var body: some View{
        HStack(spacing: 20){
            Image(systemName: "flag.fill")
                .font(.system(size: 40))
                .foregroundColor(.white)
            
            VStack(alignment: .leading, spacing: 0){
                Divider().opacity(0)

                Text("test")
                    .fontWeight(.bold)
                    .font(.system(size: 23))
                    .foregroundColor(.white)
                
                Spacer().frame(height:5)
                
                Text("test")
                    .foregroundColor(.white)
            }
        }
        .padding(30)
        .background(Color.purple)
        .cornerRadius(20)
        
        
    }
}
import SwiftUI

struct MyProject: View{
    
    var icon : String
    var title : String
    var start: String
    var end : String
    var bgColor : Color
    
    var body: some View{
        HStack(spacing: 20){
            Image(systemName: icon)
                .font(.system(size: 40))
                .foregroundColor(.white)
            
            VStack(alignment: .leading, spacing: 0){
                Divider().opacity(0)
//                Rectangle.frame(height:0)
                Text(title)
                    .fontWeight(.bold)
                    .font(.system(size: 23))
                    .foregroundColor(.white)
                
                Spacer().frame(height:5)
                
                Text("\(start) - \(end)")
                    .foregroundColor(.white)
            }
        }
        .padding(30)
        .background(bgColor)
        .cornerRadius(20)
        
        
    }
}

티스토리 첨부 용량때문에 FPS랑 Quality 낮췄더니 움짤이 기어가는 중

profile

Devlog

@덩이

포스팅이 좋았다면 "좋아요❤️" 또는 "구독👍🏻" 해주세요!

검색 태그