小编has*_*o11的帖子

带有通知中心发布者的 SwiftUI

我想在应用程序进入后台并返回时收听通知。我正在尝试使用 NotificationCenter 发布者并让 SwiftUI 视图收听它们。
我可以使用几种方法来做到这一点,我正在尝试使用其中的两种方法,但有趣的是,尽管当我将订阅者放入init()方法中时,所有方法看起来都是合法的,但它不起作用。
我试图把它放在main线程上,但仍然没有成功。
有谁知道为什么?
这是我的代码:

struct ContentView: View {
    @State var isActive = true
    @State var cancellables = Set<AnyCancellable>()
    var body: some View {
        ZStack {
            Image("background")
                .resizable()
                .scaledToFill()
                .edgesIgnoringSafeArea(.all)                        
        }
        .onReceive(NotificationCenter.default.publisher(for: UIApplication.willResignActiveNotification)) { _ in
            self.isActive = false
        }
        .onReceive(NotificationCenter.default.publisher(for: UIApplication.willEnterForegroundNotification), perform: {_ in
            self.isActive = true
        })
    }

    init() {
        NotificationCenter.default.publisher(for: UIApplication.willResignActiveNotification)
         //   .receive(on: RunLoop.main)
            .sink(receiveValue: { _ in
                print("init")
            }
            .store(in: &cancellables)
    }
}
Run Code Online (Sandbox Code Playgroud)

奇怪的是,onReceive修饰符中的侦听器就像一个魅力。在init()该 …

notificationcenter swiftui combine

9
推荐指数
1
解决办法
4745
查看次数

SwiftUI 文本对齐对齐

有没有人找到一种方法以Text合理的方式将字符串对齐?

在我的阅读应用,我想向用户提供选择合理的定位,其中两个在.leading两个.trailing比对是真正的在同一时间。不幸的是, 的.multilineTextAlignment修饰符Text只有三个选项:.leading,.center.trailing

如果没有,我仍然可以将 an 包装UILabel到 a 中,UIViewRepresentable因为UILabel.justified对齐选项,但我认为它也应该在 the 中可用,但我Text找不到它。

text text-alignment swiftui

5
推荐指数
1
解决办法
502
查看次数