如果对你有帮助,谢谢!
知识点目录
本文总结了使用SwiftUI开发的一系列小的知识点,旨在帮助你快熟开发,解决问题。
提示:需掌握Swift基本语法!
1, json解析处理Null值
可以说这个问题是比较恶心的一个问题,后端 Java 会直接把 null 返回,给刚接触iOS开发者带来一定困扰。我也查了一圈资料才得到解决方案。
//json格式
{
"data": "1784", //
"message": "成功",
"status": 200
}
失败情况
{
"data": null,
"message": "短信已发送,请稍后重试",
"status": 500
}
struct VerifiedCode: Codable {
let status: Int
// let data: String
private let data: String? // <- This should be optional, otherwise it will fail decoding
var defaultedName: String { data ?? "Orange" }
let message: String
}
2, Data打印输出
print("Data: \(data)")
print("Data include nsdata: \(NSData(data: data))")
print("Data include string: \(String(describing: data))")
let str = String(data:data, encoding: String.Encoding.utf8)
print("Data to String: \(String(describing: str))")
/*-----打印结果-----*/
Data: 47 bytes
Data include nsdata: {length = 47, bytes = 0x7b226461 7461223a 22313037 34222c22 ... 7573223a 3230307d }
Data include string: 47 bytes
Data to String: Optional("{\"data\":\"1074\",\"message\":\"成功\",\"status\":200}")
3, 扩大点击热区
VStack{
Text("点击")
}.frame(width: 200, height: 200)
// .background(Color.purple) //加上颜色可以让点击区域生效
.contentShape(Rectangle()) //没有颜色的情况用contentShape扩大点击响应区域
.onTapGesture {
print("tap")
}
4, 渐变 (三种效果)
//线性渐变
Text("已实名")
.frame(width:64, height:23)
.font(.system(size: 12))
.background(LinearGradient(gradient: Gradient(colors: [Color.hexColorString( "#FAD961"), Color.hexColorString( "#FF975D")]),startPoint: .bottomTrailing,endPoint: .topLeading).cornerRadius(12))
VStack {
LinearGradient(gradient: Gradient(colors: [.white, .black]), startPoint: .leading, endPoint: .trailing)
RadialGradient(gradient: Gradient(colors: [.blue, .black]), center: .center, startRadius: 20, endRadius: 200)
// 同Android中 SweepGradient
AngularGradient(gradient: Gradient(colors: [.red, .yellow, .green, .blue, .purple, .red]), center: .center)
}
5, 打电话
let numberString = "111-222-3334"
Button(action: {
let telephone = "tel://"
let formattedString = telephone + numberString
guard let url = URL(string: formattedString) else { return }
UIApplication.shared.open(url)
}) {
Text(numberString)
}
6, Alter弹窗
@State private var showingAlert = false
MineItemView(mineitem: mineitems[4], description: "17343101261")
.alert(isPresented: $showingAlert) {
Alert(title: Text(""), message: Text("17343101261"),
primaryButton: .default(Text("拨打"),action:{
guard let number = URL(string: "tel://" + "17343101261") else { return }
UIApplication.shared.open(number)
}),
secondaryButton: .default(Text("取消")))
}
.onTapGesture {
self.showingAlert = true
}
其他问题
1,xcode archive灰色,无法打包的解决办法
解决办法:目前的运行配置是使用模拟器,改成“iOS Device”即可 。
2,