궁금한 내용을 검색해보세요!
이 포스팅은 쿠팡 파트너스 활동의 일환으로, 이에 따른 일정액의 수수료를 제공받습니다.
서근 개발노트
티스토리에 팔로잉
SWIFTUI/Controls

SwiftUI : Alert (알림 메세지)

서근
QUOTE THE DAY

“ 백 권의 책에 쓰인 말보다, 한 가지 성실한 마음이 더 크게 사람을 움직인다. ”

- Franklin (프랭클린)
Written by SeogunSEOGUN

SwiftUI : Alert (알림 메세지)

iOS 15 버전 부터 더이상 아래 형태로 사용 되지 않습니다. ( 업데이트 예정)

 

Alert 대해 알아보도록 합시다.

Alert

AlertSwiftUI에서 UIKitUIAlertView와 동일합니다. SwiftUI에서 어떻게 경고메세지를 만들고 표시하는지 알아봅시다.

기본 코드

swift
UNFOLDED
.alert(isPresented: $____) {
Alert(title: Text(""), message: nil, dismissButton: .defalut(Text("")))
}

Alert 사용 조건

  1.  Alert를 표시할지에 대한 여부를 지정하는 Bool binding (state)
  2.  Alert를 반환하는 closure

SwiftUIbool 값이 상태이기 때문에 변경 될 때마다 뷰를 새로 고칩니다. 결과적으로 true로 설정된 경우 Alert가 표시됩니다.만약 Alert가 해제되면 bool 값이 자동으로 false로 설정됩니다.

swift
UNFOLDED
.alert(isPresented: $someState) {
Alert(title: Text(""), message: nil, dismissButton: .defalut(Text("")))
}

버튼을 클릭했을때 나오는 메세지는  Title: Text 에 적고, 확인 후 밖으로 빠져 나오는 버튼 메세지를  dismissButton: Text 에 적어줍니다.

swift
UNFOLDED
struct ContentView: View {
//showAlert의 bool 타입을 false로 설정
@State private var showingAlert = false
var body: some View {
Button("Alert 메세지") {
self.showingAlert.toggle()
}
.foregroundColor(.white)
.padding()
.background(Color.green)
.cornerRadius(30)
.font(.system(size: 30))
.alert(isPresented: $showingAlert) {
Alert(title: Text("서근 개발블로그"), message: nil,
dismissButton: .default(Text("구독")))
}
}
}

SwiftUI : Alert (알림 메세지) - Alert - Alert 사용 조건

두 가지 버튼 추가 

primaryButton: .destructive, secondaryButton: .cancel 로 경고 메세지에 두가지 버튼을 추가 할 수 있습니다.

swift
UNFOLDED
.alert(isPresented: $showingAlert) {
Alert(title: Text(""), message: Text(""), primaryButton: .destructive(Text("취소"), action: {
//some Action
}), secondaryButton: .cancel(Text("")))
}

이 방법을 사용한 코드는 다음과 같습니다.

swift
UNFOLDED
struct ContentView: View {
@State private var showingAlert = false
var body: some View {
Button(action: {
self.showingAlert.toggle()
}) {
Text("서근개발블로그")
.alert(isPresented: $showingAlert) {
Alert(title: Text("서근 개발 블로그"), message: Text("열심히 하겠습니다."), primaryButton: .destructive(Text("취소"), action: {
//some Action
}), secondaryButton: .cancel(Text("좋아요")))
}
}
}
}

SwiftUI : Alert (알림 메세지) - Alert - 두 가지 버튼 추가 

Alert property에 letreturn 값으로 경고 메세지가 나왔을때, 두가지의 버튼을 만들 수 있습니다.

swift
UNFOLDED
.alert(isPresented: $_____) {
let SomeButton1 = Alert.Button.default(Text("구독")) {
//print("primary button pressed")
}
let SomeButton2 = Alert.Button.cancel(Text("좋아요")) {
//print("secondary button pressed")
}
return Alert(title: Text("서근 개발블로그"),
message: Text("구독과 좋아요중에 선택해주세요"),
primaryButton: SomeButton1Button, secondaryButton: SomeButton2Button)
}

전체코드는 아래와 같고, 아래 코드를 작성하게 되면 이와 같은 버튼을 확인 할 수 있습니다. 

swift
UNFOLDED
struct ContentView: View {
//showAlert의 bool 타입을 false로 설정
@State private var showingAlert = false
var body: some View {
Button("Alert 메세지") {
self.showingAlert.toggle()
}
.foregroundColor(.white)
.padding()
//그라데이션
.background(LinearGradient(gradient: Gradient(colors: [Color.red, Color.blue]), startPoint: .leading, endPoint: .trailing))
.cornerRadius(30)
.font(.system(size: 30))
.alert(isPresented: $showingAlert) {
let firstButton = Alert.Button.default(Text("구독")) {
print("primary button pressed")
}
let secondButton = Alert.Button.cancel(Text("좋아요")) {
print("secondary button pressed")
}
return Alert(title: Text("서근 개발블로그"),
message: Text("구독과 좋아요중에 선택해주세요"),
primaryButton: firstButton, secondaryButton: secondButton)
}
}
}

SwiftUI : Alert (알림 메세지) - Alert - 두 가지 버튼 추가 

 

 

읽어주셔서 감사합니다🤟


잘못된 내용이 있으면 언제든 피드백 부탁드립니다.

'SWIFTUI > Controls' 카테고리의 다른 글

SwiftUI : Text  (0) 2021.04.29
SwiftUI : Toggle Switch (toggleStyle)  (0) 2021.03.18
SwiftUI : EditButton [onDelete, OnMove]  (1) 2021.01.23
SwiftUI : Button / onTapGesture  (4) 2021.01.23
SwiftUI : TextEditor  (0) 2021.01.21


서근


위처럼 이미지 와 함께 댓글을 작성할 수 있습니다.