
Link에 대해 알아보도록 합시다.
Link
SwiftUI에서는 Link
버튼을 누르면 Safari
에서 URL
을 기능을 제공합니다.
사용 방법은 간단합니다. 아래 코드와 같이 버튼의 제목과 표시 할 URL
주소를 지정하면됩니다.
swift
UNFOLDEDLink("Learn SwiftUI", destination: URL(string: "https://seons-dev.tistory.com/")!) //주소위에 '!' 옵셔널
이미지
또는 SF Symbols
를 활용해서 링크 버튼을 만들 수 있습니다.
swift
UNFOLDED Link(destination: URL(string: "https://seons-dev.tistory.com/")!) { HStack { Text("서근 개발블로그") Image(systemName: "tortoise.fill") .font(.largeTitle) } .foregroundColor(.black) }

예제
swift
UNFOLDED VStack { Link(destination: URL(string: "https://seons-dev.tistory.com")!, label: { Text("서근 개발노트") .font(.system(size: 30)) .frame(width: 300, height: 60) .background(Color.black) .foregroundColor(.white) .cornerRadius(20) .padding() })

위 처럼 링크 버튼을 만들고 Form
을 사용해서 또 다른 링크를 추가 할 수 있습니다.
swift
UNFOLDEDstruct ContentView: View { var body: some View { VStack { Link(destination: URL(string: "https://seons-dev.tistory.com")!, label: { Text("서근 개발노트") .font(.system(size: 30)) .frame(width: 300, height: 60) .background(Color.black) .foregroundColor(.white) .cornerRadius(20) .padding() }) Form{ Link("SwiftUI 튜토리얼 모음", destination: URL(string: "https://seons-dev.tistory.com/notice/48")!) Link("Xcdoe 단축키 모음", destination: URL(string: "https://seons-dev.tistory.com/56")!) } } } }

OpenURL
또는 openURL
를 사용하여 코드에서 URL
을 열 수 있습니다. 여기에서는 Struct
아래 다음 코드를 먼저 추가해줘야 합니다.
swift
UNFOLDEDstruct ContentView: View { @Environment(\.openURL) var openURL var body: some View { ... }
swift
UNFOLDED Button("이름지정") { openURL(URL(string: "https://주소")!) }
@Environment?
@Environment 이라고 불리고, 외부에서 우리에게 제공된 값을 저장하는 속성을 만들 수 있습니다. 쉽게 말해서
"사용자가 lightMode입니까, DarkMode 모드입니까?", "더 작거나 더 큰 글꼴을 요구 했습니까?", "어떤 시간대에 있습니까?"
라는 변화에 제공된 값을 주는것이죠.
swift
UNFOLDEDstruct ContentView: View { @Environment(\.openURL) var openURL var body: some View { //버튼을 만들어주고 Button("Visit Apple") { //openURL을 추가해준다. openURL(URL(string: "https://seons-dev.tistory.com")!) } } }
결과 화면은 위 gif
화면과 같습니다.
읽어주셔서 감사합니다🤟
잘못된 내용이 있으면 언제든 피드백 부탁드립니다.
'SWIFTUI > WebView' 카테고리의 다른 글
SwiftUI : Map View (0) | 2021.03.08 |
---|---|
SwiftUI : VideoPlayer (2) | 2021.01.31 |
SwiftUI : WebView 생성(코드) (0) | 2021.01.27 |