ios - 如何在 SwiftUI 中使用复选框创建文本?

标签 ios swift checkbox swiftui

我有一个带有文本字段的复选框(✅如待办事项列表)的要求。目前我已经创建了如下按钮对象:

    Button(action: {
            // do when checked / unchecked
            //...
    }) {
        HStack(alignment: .top, spacing: 10) {

            Rectangle()
                .fill(Color.white)
                .frame(width:20, height:20, alignment: .center)
                .cornerRadius(5)
            Text("Todo  item 1")
        }
    }

我需要在 SwiftUI 中保留 checkedunchecked 状态。

checkbox sample image

最佳答案

这是我创建的一个简单、可重复使用的复选标记组件,它遵循类似于 iOS 上其他复选标记的配色方案(例如,在“消息”应用中选择消息):

import SwiftUI

struct CheckBoxView: View {
    @Binding var checked: Bool

    var body: some View {
        Image(systemName: checked ? "checkmark.square.fill" : "square")
            .foregroundColor(checked ? Color(UIColor.systemBlue) : Color.secondary)
            .onTapGesture {
                self.checked.toggle()
            }
    }
}

struct CheckBoxView_Previews: PreviewProvider {
    struct CheckBoxViewHolder: View {
        @State var checked = false

        var body: some View {
            CheckBoxView(checked: $checked)
        }
    }

    static var previews: some View {
        CheckBoxViewHolder()
    }
}

您可以像这样在其他 View 中使用它:

...
@State private var checked = true
...

HStack {
    CheckBoxView(checked: $checked)
    Spacer()
    Text("Element that requires checkmark!")
}
...

关于ios - 如何在 SwiftUI 中使用复选框创建文本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58425829/

相关文章:

javascript - jQuery:检测复选框是否被选中的问题

ios - 访问自定义 cocoapod 内的 pod

ios - 禁用TableView单元格

ios - ViewController Hierarchy - 从堆栈中移除 UISplitviewController

ios - GCD后台任务最大TTL

ios - 从 AppDelegate 发送本地通知时出现 NSInvalidArgumentException

ios - 在 Swift 中将音频转换为二进制数据

ios - 添加 View 时发出 sigabrt 信号

php - 使用 jQuery 选择表中的所有复选框

javascript - 动态添加表单和输入复选框到 HTML 问题