天天看點

swift學習筆記 cs193p lectrue1

cs193p swift第一課

首先用Xcode建立檔案,MemorizeApp的原始代碼如下:

import SwiftUI

@main
struct MemorizeApp: App {
    var body: some Scene {
        WindowGroup {
            ContentView()
        }
    }
}
           

ContentView的代碼如下:

//
//  ContentView.swift
//  Memorize
//
//  Created by 趙炫皓 on 2022/8/7.
//

import SwiftUI

struct ContentView: View {
    var body: some View {
        Text("Hello, world!")
            .padding()
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

           

其中下半部分在實踐中幾乎沒有作用,隻是單純地拷貝ContentView(),是以在撰寫代碼的過程中可以将其隔開

該代碼效果如圖:

swift學習筆記 cs193p lectrue1

ContentView中 主體類型就像一個視圖:

var body: some View

其中的元素Text像是lego積木,是組成完整視圖的一個部分。

Text("Hello, world!") .padding()

是一種隐式的傳回語句,可以在前面加上return,傳回text.

ZStack

像是lego積木包一樣,包含一種組合好的,設計好的元素,友善使用。是以在實踐過程中,可以這樣寫:

struct ContentView: View {
    var body: some View {
      return ZStack(content:{
        RoundedRectangle(cornerRadius: 20)
        		.stroke(lineWidth: 3)
        		.padding(.horizontal)
        		.foregroundColor(.red)
        
        Text("Hello world!")
        		.forgroundColor(.orange)
        		.padding()
      })
    }
}
           

也可以在ZStack外部寫一些條件:

struct ContentView: View {
    var body: some View {
      return ZStack(content:{
        RoundedRectangle(cornerRadius: 20)
        		.stroke(lineWidth: 3)
        
        Text("Hello world!")
        		.foregroundColor(.orange)
      })
      		.padding(.horizontal)
        	.foregroundColor(.red)
    }
}
           

效果如圖:

swift學習筆記 cs193p lectrue1

繼續閱讀