没有按钮的 SwiftUI 安排本地通知?

编程入门 行业动态 更新时间:2024-10-27 06:28:54
本文介绍了没有按钮的 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 安排本地通知?

本文发布于:2023-11-27 02:00:18,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1636106.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:按钮   通知   SwiftUI

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!