Swift & SwiftUI Tips 02

Cover

Swift

Date 和 DateComponents 转换

1
2
3
let calendar = Calendar.current
let components = calendar.dateComponents([.year, .month, .day], from: date)
let date = calendar.date(from:components)

判断键盘是否支持Emoji输入

1
2
3
4
5
6
7
var isEmojiKeyboardSupoprted: Bool {
UITextInputMode.activeInputModes.map({ mode in
mode.primaryLanguage
}).first(where: { language in
language == "emoji"
}) != nil
}

UITextField 隐藏光标

1
2
3
override func caretRect(for position: UITextPosition) -> CGRect {
.zero
}

时间格式化、FormatStyle

日期时间格式化及iOS FormatStyle Tips

子线程执行异步任务,回调主线程

1
2
3
4
5
6
DispatchQueue.global().async {
print(Thread.current)
DispatchQueue.main.async {
print(Thread.current)
}
}

延迟执行异步任务

1
2
3
DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
// your code
}

获取对象地址

1
2
// 获取对象地址:
print(Unmanaged.passUnretained(instance).toOpaque())

获取当前是否为暗色模式

1
2
3
4
5
6
7
if #available(iOS 13.0, *) {
if UITraitCollection.current.userInterfaceStyle == .dark {
print("Dark mode")
} else {
print("Light mode")
}
}

getOrDefault in Swift

从 Dictionary 中取值,如果不存在则返回默认值

1
let list = dic["keyOfList", default: []]

SwiftUI

1
2
3
4
5
6
7
8
9
struct ContentView: View {
var body: some View {
Menu("Options") {
Button("Option 1") { }
Button("Option 2") { }
Button("Option 3") { }
}
}
}

TabView 中使用 SFSymbol 默认会被替换成“fill”变体

使用 selection 来判断是否选中从而切换icon。注入 environment

1
2
3
4
5
6
7
8
9
10
11
12
13
14
TabView(selection: $selectedItem) {
NavigationView {
TabContent1()
}.tabItem {
if selectedItem == 1 {
Label("Tab 1", systemImage: "square.fill.on.square.fill")
} else {
Label("Tab 1", systemImage: "square.on.square")
.environment(\.symbolVariants, .none)
}
}.tag(1)

// ...
}

HStack 中的 Button 会同时响应事件

1
2
Button()
.buttonStyle(BorderlessButtonStyle())

让 View 撑满屏幕

1
2
3
Text("SwiftUI Tutorials")
.font(.title)
.frame(maxWidth: .infinity, maxHeight: .infinity)

在 ForEach 循环中获取 index

1
2
3
4
ForEach(Array(array.enumerated()), id: \.element) { index, element in
Text("\(index)")
Text(element.description)
}

其他

Python

1
2
3
4
5
6
7
8
9
10
11
12
13
14
# 获取参数 
import sys

sys.argv # 参数列表
sys.argv[0] # 脚本文件名
sys.argv[1] # 第一个参数


# 创建目录

import os

os.path.exists(path)
os.makedirs(path)

macOS 唤起 Emoji 输入面板

快捷键

1
Command + Control + Space