自定义Alert

为什么

在iOS中,Alerts不能包含图像或文本以外的任何内容。 这允许您使用任何自定义视图轻松自定义消息部分。

虽然Alert是在SwiftUI中完全重建的,但它的设计外观和行为与原生alert完全相同。 该Alert使用自己的窗口显示,并利用辅助功能缩放,但具有自定义视图的优势。

如果内容太大(因为文本太长)或者文本由于辅助功能缩放而无法适应,则内容将像SwiftUI Alert中一样滚动。

用法

SwiftUI Alert 自定义 Alert
Native Alert Custom Alert

您可以轻松地添加图像或更改Alert中使用的字体,或者您可以想象的任何其他内容。

带图像和文本字段的简单示例

或更复杂的布局

API与SwiftUI Alerts非常相似

.customAlert("Some Fancy Alert", isPresented: $showAlert) {
    Text("I'm a custom Message")
        .font(.custom("Noteworthy", size: 24))
    Image(systemName: "swift")
        .resizable()
        .scaledToFit()
        .frame(maxHeight: 100)
        .foregroundColor(.blue)
} actions: {
    Button {
        // some Action
    } label: {
        Label("Swift", systemImage: "swift")
    }
    
    Button(role: .cancel) {
        // some Action
    } label: {
        Text("Cancel")
    }
}

您可以使用MultiButton创建并排按钮

.customAlert("Alert with Side by Side Buttons", isPresented: $showAlert) {
    Text("Choose left or right")
} actions: {
    MultiButton {
        Button {
            // some Action
        } label: {
            Text("Left")
        }

        Button {
            // some Action
        } label: {
            Text("Right")
        }
    }
}

可以通过Environment自定义Alert

.configureCustomAlert { configuration in
    // Adapt the default configuration
}

您也可以在线显示Alert,例如在List

CustomAlertRow {
    // Content
} actions: {
    // Actions
}

安装

SwiftPM

https://github.com/divadretlaw/CustomAlert.git

许可证

请参阅 LICENSE

版权所有 © 2024 David Walter (www.davidwalter.at)