2021年开发笔记第一期
iOS13
之后怎么获取Key Window
static var keyWindow:UIWindow? {
if #available(iOS 13.0, *) {
return UIApplication.shared.connectedScenes
.filter({$0.activationState == .foregroundActive})
.compactMap({$0 as? UIWindowScene})
.first?.windows
.filter({$0.isKeyWindow})
.first
} else {
return UIApplication.shared.windows
.filter({$0.isKeyWindow})
.first
}
}
'xxx_App' is annotated with @main and must provide a main static function of type () -> Void or () throws -> Void. Inheritance from non-protocol type 'App'
谷歌了半天,很多人都遇到过,但是都不能解决我的问题,后来研究发现,我项目存在一样的App
名字的Struct
,带上模块名字就修复了。
@main
struct Win_App: SwiftUI.App {
...
}
SwiftUI
怎么在任何 Function
中实行跳转
struct ContentView: View {
/// 控制何时进行跳转
@State var action: Bool = false
var body: some View {
NavigationView {
HStack(spacing:0) {
/// NavigationLink 返回 `EmptyView` 不污染界面
NavigationLink(destination: destination, isActive: $action) {
EmptyView()
}
Text("Click me!")
.onTapGesture {
self.clicked()
}
}
}
}
func clicked() {
/// 执行跳转
action = true
}
}
隐藏返回按钮文本
let backButtonAppearance = UIBarButtonItemAppearance()
backButtonAppearance.normal.titleTextAttributes = [
.font : UIFont.systemFont(ofSize: 0),
]
appearance.backButtonAppearance = backButtonAppearance
修改 SwiftUI
返回按钮的颜色
NavigationView {
...
}
.accentColor(.black)
需要注意的是官方说
accentColor
已经要废弃了,Use the asset catalog's accent color or View.tint(_:) instead."
但是替换为
tint
不起作用。
隐藏 SwiftUI 的 UITabbar
需要在需要隐藏界面进行设置
struct PalletBindBoxNumberPage: View {
...
var body: some View {
...
.onAppear {
App.tabBar?.isHidden = true
}
.onDisappear {
App.tabBar?.isHidden = false
}
}
}
struct App {
static var keyWindow:UIWindow? {
if #available(iOS 13.0, *) {
return UIApplication.shared.connectedScenes
.filter({$0.activationState == .foregroundActive})
.compactMap({$0 as? UIWindowScene})
.first?.windows
.filter({$0.isKeyWindow})
.first
} else {
return UIApplication.shared.windows
.filter({$0.isKeyWindow})
.first
}
}
static var tabBar:UITabBar? {
return keyWindow?.rootViewController
.flatMap({$0.view})
.flatMap({$0.subviews.first})
.flatMap({$0.subviews.first})
.map({$0.subviews})
.map({$0.compactMap({$0 as? UITabBar})})
.flatMap({$0.first})
}
}
巧妙利用 flatMap 和 Map 进行解包
比如我有下面的一个结构
struct Model {
let age:Int?
}
let model:Model?
此时我想让age
显示在文本中,你可能这么写
if let age = model?.age {
Text("\(age)")
} else {
Text("")
}
但是使用flatMap
和map
进行解包
Text(model.flatMap({$0.age}).map({"\($0)"}) ?? "")