之前一直使用的OC,現在也有不少人使用Swift,我也嘗試一下,寫一個簡單又基礎的功能:頁面的跳轉和返回。這里將顯示幾個swift文件的代碼。
文件Common.swift的代碼:
//
// Common.swift
// MySwiftProject
//
// Created by ChengJh on 2024/5/15.
// Copyright ? 2024 CompanyName. All rights reserved.
//import SwiftUIextension Color {/* 使用示例:let customColor = Color(hex: "#123456"); */init(hex: String) {let scanner = Scanner(string: hex)/* 下劃線的作用:我們不關心后面函數返回的結果, 所以使用下劃線忽略它。 */_ = scanner.scanString("#") // 跳過'#'字符。var rgbValue: UInt64 = 0scanner.scanHexInt64(&rgbValue)let r = Double((rgbValue & 0xFF0000) >> 16) / 255.0let g = Double((rgbValue & 0xFF00) >> 8) / 255.0let b = Double(rgbValue & 0xFF) / 255.0self.init(red: r, green: g, blue: b)}}
文件ContentView.swift的代碼:
//
// ContentView.swift
// MySwiftProject
//
// Created by ChengJh on 2024/5/15.
//import SwiftUIstruct ContentView: View {var body: some View {
#if DEBUG// 打印日志。print("test-log");
#endifreturn NavigationView {VStack(alignment: .center) {Text("Hello, world!")NavigationLink(destination: SecondView()) {Text("Enter SecondView")// foregroundColor設置文字顏色。.foregroundColor(.white).padding(10)}.background(Color(hex: "#4982f5")).border(.red, width: 2).cornerRadius(5)// Spacer是一個占據剩余空間的視圖元素, 可以幫助我們實現更靈活的布局。Spacer()}.frame(width: UIScreen.main.bounds.width).padding(EdgeInsets(top: 50, leading: 0, bottom: 0, trailing: 0)).background(Color("#f3f3f3"))//.background(.orange).navigationBarHidden(false).navigationViewStyle(.stack).navigationBarTitle("首頁", displayMode: .inline);}}
}struct ContentView_Previews: PreviewProvider {static var previews: some View {// 注: 若內容體只有一條語句 則可省略關鍵字return。ContentView()}
}
文件SecondView.swift的代碼:
//
// SecondView.swift
// MySwiftProject
//
// Created by ChengJh on 2024/5/15.
// Copyright ? 2022 CompanyName. All rights reserved.
//import SwiftUIstruct SecondView: View {@Environment(\.presentationMode) var presentationMode;var body: some View {
#if DEBUG// 打印日志。print("second-log");
#endifreturn VStack {Text("Hello, second!").padding()Button("Goback") {presentationMode.wrappedValue.dismiss();}//Spacer是一個占據剩余空間的視圖元素, 可以幫助我們實現更靈活的布局。Spacer()}.navigationBarTitle("Second");}
}