Hôm nay cafedev sẽ giới thiệu một cách ngắn ngọn và cực dễ hiểu về Alert trong SwiftUI để các bạn có thể thực hành nó một cách nhanh chóng nhất có thể. Vì một thế giới dev luôn thay đổi từng ngày.
Lưu ý: Bài này sẽ được cập nhật (kiến thức, demo) liên tục cho tới khi Alert được ổn định nhất.
Nội dung chính
Khái niệm
Một container view cho một đoạn văn cảnh báo nào đó
Một số demo cơ bản
- Chúng ta có thể hiển thị Alert thông qua biến bool
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// ContentView.swift | |
// SwiftUISample | |
// | |
// Created by Cafedev on 10/6/19. | |
// Copyright © 2019 Cafedev.vn All rights reserved. | |
// | |
import SwiftUI | |
struct ContentView: View { | |
@State var isError: Bool = false | |
var body: some View { | |
Button("Alert") { | |
self.isError = true | |
}.alert(isPresented: $isError, content: { | |
Alert(title: Text("Cafedev Error"), message: Text("Cafedev is overload request - Error Reason"), dismissButton: .default(Text("OK"))) | |
}) | |
} | |
} | |
struct ContentView_Previews: PreviewProvider { | |
static var previews: some View { | |
ContentView() | |
} | |
} |
- Binding dữ liệu bằng
Identifiable
item
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@State var error: AlertError? | |
var body: some View { | |
Button("Alert Error") { | |
self.error = AlertError(reason: "Cafedev is overloading") | |
}.alert(item: $error, content: { error in | |
alert(reason: error.reason) | |
}) | |
} | |
func alert(reason: String) -> Alert { | |
Alert(title: Text("Error"), | |
message: Text(reason), | |
dismissButton: .default(Text("OK")) | |
) | |
} | |
struct AlertError: Identifiable { | |
var id: String { | |
return reason | |
} | |
let reason: String | |
} |
Các bài Demo nâng cao
Đang cập nhật