SwiftUI开发小技巧总结(不定期更新)

5,589 阅读3分钟

目前SwiftUI还不完善,而且实际使用还会存在一些缺陷。网上的教程目前还很少,有也是收费的。因此特地整理一些平时开发中遇到的问题,免费提供给读者。

(注:本文主要面向对SwiftUI有一定基础的读者,转载请注明出处。)

调整状态栏样式 StatusBarStyle

尝试Info.plistUIApplication.statusBarStyle方法无效。如果有UIViewController作为根视图,重写方法preferredStatusBarStyle,这样可以控制全局;如果要设置单个页面的样式用preferredColorScheme(.light),但测试似乎设置无效。还有另一个方法:stackoverflow.com/questions/5…

调整导航栏样式 NavigationBar

let naviAppearance = UINavigationBarAppearance()
naviAppearance.configureWithOpaqueBackground()              // 不透明背景样式
naviAppearance.backgroundColor = UIColor.whiteColor         // 背景色
naviAppearance.shadowColor = UIColor.whiteColor             // 阴影色
naviAppearance.titleTextAttributes = [:]                    // 标题样式
naviAppearance.largeTitleTextAttributes = [:]               // 大标题样式
UINavigationBar.appearance().standardAppearance = naviAppearance
UINavigationBar.appearance().compactAppearance = naviAppearance
UINavigationBar.appearance().scrollEdgeAppearance = naviAppearance
UINavigationBar.appearance().tintColor = UIColor.blackColor // 导航栏按钮颜色

注意configureWithOpaqueBackground()需要在其它属性设置之前调用,除此之外还有透明背景configureWithTransparentBackground(),设置背景模糊效果backgroundEffect(),背景和阴影图片等,以及导航栏按钮样式也可修改。

调整标签栏样式 TabBar

let itemAppearance = UITabBarItemAppearance()
itemAppearance.normal.iconColor = UIColor.whiteColor    // 正常状态的图标颜色
itemAppearance.normal.titleTextAttributes = [:]         // 正常状态的文字样式
itemAppearance.selected.iconColor = UIColor.whiteColor  // 选中状态的图标颜色
itemAppearance.selected.titleTextAttributes = [:]       // 选中状态的文字样式
let tabBarAppearance = UITabBarAppearance()
tabBarAppearance.configureWithOpaqueBackground()        // 不透明背景样式
tabBarAppearance.stackedLayoutAppearance = itemAppearance
tabBarAppearance.backgroundColor = UIColor.whiteColor   // 背景色
tabBarAppearance.shadowColor = UIColor.clear            // 阴影色
UITabBar.appearance().standardAppearance = tabBarAppearance

注意configureWithOpaqueBackground()同样需要在其它属性设置之前调用,和UINavigationBarAppearance一样有同样的设置,除此之外还可以为每个标签项设置指示器外观。

标签视图 TabView

设置默认选中页面:方法如下,同时每个标签项需要设置索引值tag()

TabView(selection: $selectIndex, content: {})

控制底部标签栏显示和隐藏:

UITabBar.appearance().isHidden = true

NavigationView与TabView结合使用时,进入子页面TabBar不消失问题:不用默认的TabBar,将其隐藏,自己手动实现一个TabBar,放在根视图中。

(转载请注明出处:https://juejin.cn/post/7037780197076123685)

键盘

输入框获得焦点(弹出键盘):在iOS15上增加了方法focused(),注意这个方法在视图初始化时是无效的,需要在onAppear()中延迟一定时间调用才可以。在此之前的系统只能自定义控件的方法实现参考这个:stackoverflow.com/questions/5…

关闭键盘,两种方法都可以:

UIApplication.shared.keyWindow?.endEditing(true)
UIApplication.shared.sendAction(#selector(UIResponder.resignFirstResponder), to: nil, from: nil, for: nil)

添加键盘工具栏:

.toolbar()

手势

获得按下和松开的状态:

.simultaneousGesture(
    DragGesture(minimumDistance: 0)
        .onChanged({ _ in })
        .onEnded({ _ in })
)

通过代码滚动ScrollView到指定位置:借助ScrollViewReader可以获取位置,在onAppear()中设置位置scrollTo(),我们实际使用发现,需要做个延迟执行才会有效,可以把执行放在DispatchQueue.main.async()中执行。

TextEditor

修改背景色:

UITextView.appearance().backgroundColor

处理Return键结束编辑:

.onChange(of: text) { value in
    if value.last == "\n" {
        UIApplication.shared.keyWindow?.endEditing(true)
    }
}

Text文本内部对齐方式

multilineTextAlignment(.center)

(转载请注明出处:https://juejin.cn/post/7037780197076123685)

页面跳转

容易出错的情况:开发中会经常遇到这样的需求,列表中选择一项,进入子页面。点击按钮返回上一页。此时再次点击列表中的某一项,会发现显示的页面内容是错误的。如果你是用NavigationLink做页面跳转,并传递了isActive参数,那么是会遇到这样的问题。原因在于多个页面的使用的是同一个isActive参数。解决办法是,列表中每一项都用独立的变量控制。NavigationView也尽量不要写在TabView外面,可能会导致莫名其妙的问题。

属性包装器在init中的初始化

init方法中直接赋值会发现无法成功,应该用属性包装器自身的方法包装起来,赋值的属性名前加_,例如:

_value = State<Int>(initialValue: 1)
_value = Binding<Bool>.constant(true) // 也可以使用Swift语法特性直接写成.constant(true)

View如何忽略触摸事件

allowsHitTesting(false)