SwiftletRadioButtonPicker,适用于 Swift 和 SwiftUI

创建一个跨平台的单选按钮选择器,允许用户从一小组选项中进行选择,通过呈现一个 SwiftletRadioButton 对象列表,用户可以点击这些对象来从列表中选择一个项目。

支持

如果您觉得 SwiftletRadioButton 有用,并希望帮助支持其持续开发和维护,请考虑进行少量捐赠,尤其是在您将其用于商业产品中时。

Buy Me A Coffee

正是通过像您这样的贡献者的支持,我才能继续免费构建、发布和维护高质量、文档完善的 Swift 包,例如 SwiftletRadioButton

安装

Swift Package Manager (Xcode 11 及以上)

  1. 在 Xcode 中,选择File > Add Package Dependency… 菜单项。
  2. 在对话框中粘贴 https://github.com/Appracatappra/SwiftletRadioButtonPicker.git
  3. 按照 Xcode 的说明完成安装。

为什么不是 CocoaPods、Carthage 或其他?

支持多个依赖管理器会使维护库的复杂性和耗时呈指数级增长。

由于 Swift Package Manager 已与 Xcode 11(及更高版本)集成,因此它是支持未来发展的最简单选择。

使用 SwiftletRadioButtonPicker

SwiftletRadioButtonPicker 在向用户呈现非常有限数量的选项时效果最佳。 例如:选择

通常,此选择器应仅用于 iOS 等平台上不超过六个选项。 当用户需要从更多选项中进行选择时,您最好使用标准的内置 SwiftUI 选择器视图之一。

示例

以下代码将在 iOS 中创建一个包含四个选项的选择器

SwiftletRadioButtonPicker(alignment: .grid, columns: 3, selection:"2")
    .radioButton(id: "0", name: "Option One")
    .radioButton(id: "1", name: "Option Two")
    .radioButton(id: "2", name: "Option Three")
    .radioButton(id: "3", name: "Option Four")

这将显示如下视图

从枚举生成

或者,您可以将任何具有原始值并符合 CaseIterable, IdentifiableEnum 提供给 radioButtons 函数,选择器将自动从 Enum 生成一个单选按钮列表。

示例

给定以下 Enum

/// Defines the format of the barcode to be generated.
public enum BarcodeFormat:String, Codable, Equatable, CaseIterable, Identifiable {
    
    /// Sepcifies a type 128 barcode.
    case code128 = "CICode128BarcodeGenerator"
    
    /// Sepcifies a type PDF 417 barcode.
    case pdf417 = "CIPDF417BarcodeGenerator"
    
    /// Sepcifies an Aztec type barcode.
    case aztec = "CIAztecCodeGenerator"
    
    /// Sepcifies a QR Code type barcode.
    case qrCode = "CIQRCodeGenerator"
    
    public var id:String {
        return rawValue
    }
    
    
    /// Sets the enum from the given `String` value.
    /// - Parameter name: The `String` name that matches a case from the enum.
    /// - Remark: Will default to `code128` if the name cannot be found.
    public mutating func fromName(_ name:String) {
        switch(name.lowercased()) {
        case "code128":
            self = .code128
        case "pdf417":
            self = .pdf417
        case "aztec":
            self = .aztec
        case "qrcode":
            self = .qrCode
        default:
            self = .code128
        }
    }
}

以及以下调用选择器的代码

SwiftletRadioButtonPicker(alignment: .grid, title:"Select barcode format:", columns: 3, selection:"code128") { button in
    card.format.fromName(button.id)
    store.refreshUI()
}
.radioButtons(from: BarcodeFormat.self)

将在 iOS 上创建一个类似于以下内容的选择器

文档

包含所有功能的完整 DocC 文档