本文介绍了没有按钮的 SwiftUI 安排本地通知?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这可能有一个非常简单的答案,因为我对 Swift 和 SwiftUI 还很陌生,并且刚刚开始学习.我正在尝试安排每天在特定时间重复的本地通知,但只有在选择了切换时才这样做.因此,如果变量为真,我希望安排该通知.我在网上看了一些教程,比如这个,但是他们都用一个按钮来显示这一点.我想使用切换而不是按钮.脚本中是否有某个地方必须这样做?为了使用切换而不是按钮,我需要做哪些不同的事情?

This may have a very simple answer, as I am pretty new to Swift and SwiftUI and am just starting to learn. I'm trying to schedule local notifications that will repeat daily at a specific time, but only do it if a toggle is selected. So if a variable is true, I want that notification to be scheduled. I looked at some tutorials online such as this one, but they all show this using a button. Instead of a button I want to use a toggle. Is there a certain place within the script that this must be done? What do I need to do differently in order to use a toggle instead of a button?

推荐答案

可以观察切换开关何时打开和关闭 -- 在 iOS 14 中可以使用 .onChange 修饰符来做这个:

You can observe when the toggle is turned on and turned off -- In iOS 14 you can use the .onChange modifier to do this:

import SwiftUI

struct ContentView: View {

    @State var isOn: Bool = false

    var body: some View {
        Toggle(isOn: $isOn, label: {
            Text("Notifications?")
        })

        /// right here!
        .onChange(of: isOn, perform: { toggleIsOn in
            if toggleIsOn {
                print("schedule notification")
            } else {
                print("don't schedule notification")
            }
        })
    }
}

对于早期版本,您可以尝试将 onReceive 与 Combine 结合使用:

For earlier versions, you can try using onReceive with Combine:

import SwiftUI
import Combine

struct ContentView: View {

    @State var isOn: Bool = false

    var body: some View {
        Toggle(isOn: $isOn, label: {
            Text("Notifications?")
        })

        /// a bit more complicated, but it works
        .onReceive(Just(isOn)) { toggleIsOn in
            if toggleIsOn {
                print("schedule notification")
            } else {
                print("don't schedule notification")
            }
        }
    }
}

您可以找到更有创意的解决方案来观察切换变化 此处.

You can find even more creative solutions to observe the toggle change here.

这篇关于没有按钮的 SwiftUI 安排本地通知?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 06:59