SwiftUI - 項(xiàng)目進(jìn)階知識(shí)點(diǎn)

前言

在學(xué)習(xí)了SwiftUI中的基本的視圖和屬性樣式以及界面布局的一下知識(shí)點(diǎn)后,我們就可以玩玩一些小項(xiàng)目了,來(lái)看看數(shù)據(jù)在SwiftUI中是怎樣傳輸或者使用的。

1、State

前面的很多例子中我們已經(jīng)使用過(guò)@State,類(lèi)似于之前使用的成員屬性一樣,不同的是@State修飾的變量不用手動(dòng)調(diào)用界面刷新,只要變量改變就會(huì)自動(dòng)刷新UI。
@State官方建議使用private,即在當(dāng)前界面使用的變量,不可以在對(duì)象間使用。

2、Binding

@Binding 可以在不同的對(duì)象間傳值。它所修飾的變量不是變量本身改變,而是變量的引用改變。
結(jié)合$xxx(投影屬性)使用在代碼中。

3、AppStorage

AppStorage類(lèi)似之前用的NSUserDefault,用于存儲(chǔ)一些輕量級(jí)的數(shù)據(jù)。是一個(gè)屬性包裝器。所存儲(chǔ)的數(shù)據(jù)是全局的。

//messageKey 相當(dāng)于key 尋找value時(shí)候用
//message 當(dāng)前變量 裝載數(shù)據(jù)
@AppStorage("messageKey") var message: String = ""

VStack{
            Text("已經(jīng)存儲(chǔ)數(shù)據(jù):\n\(message)")
            TextField("輸入保存的數(shù)據(jù)",text: $message)
                .padding(10).border(.orange, width: 2)
            Button("按鈕保存"){
                message = "按鈕保存的數(shù)據(jù)"
            }.font(.title)
        }.padding()

輸入框輸入時(shí),數(shù)據(jù)改變時(shí),本地存儲(chǔ)實(shí)時(shí)改變所存儲(chǔ)數(shù)據(jù),推出App,重新打開(kāi)數(shù)據(jù)展示為上一次輸入數(shù)據(jù)。
當(dāng)點(diǎn)擊按鈕保存數(shù)據(jù)時(shí),再次進(jìn)來(lái)就展示“按鈕保存的數(shù)據(jù)”。

相對(duì)于NSUserDefault,AppStorage使用上方便快捷,不用去setValue以及getValue操作。

另外還有一個(gè)SceneStorage,也是數(shù)據(jù)持久化方式,是SwiftUI接管的,但只能用在View上。

4、ObservableObject

所有遵循ObservableObject協(xié)議的class,就可以直接使用@Pulished 來(lái)修飾屬性,這個(gè)屬性改變后,所有使用到這個(gè)屬性的地方會(huì)自動(dòng)刷新UI。用法上類(lèi)似于前文的@State。

//放在 ContentView 范圍內(nèi)外都可以 最好方外面
class DelayUpdater: ObservableObject {
        @Published var value = 0
        init() {
            for i in 1...10 {
                DispatchQueue.main.asyncAfter(deadline: .now() + Double(i)) {
                    self.value += 1
                }
            }
        }
    }
@ObservedObject var updater = DelayUpdater()

var body: some View {
      Text("\(updater.value)").padding()
}

如果我們?cè)跀?shù)值改變前還想多做一些操作,我們可以使用willSetobjectWillChange來(lái)實(shí)現(xiàn)。

var value = 0 {
            willSet {
                //此處做另外的一些操作
                //前導(dǎo)的判斷
                //動(dòng)畫(huà)
                //調(diào)用其他方法
                objectWillChange.send()
            }
        }

這種方式可創(chuàng)造性大一點(diǎn),便于實(shí)現(xiàn)多種功能。

5、EnvironmentObject

顧名思義,就是將數(shù)據(jù)放到環(huán)境中去,這樣可以全局地從環(huán)境中獲取想要的數(shù)據(jù)。
在上面例子中新增兩個(gè)View:

struct ShowValueView: View {
    
    @EnvironmentObject var updater: DelayUpdater
    
    var body: some View {
        Text("\(updater.value)")
    }
}

struct BtnView: View {
    @EnvironmentObject var updater: DelayUpdater
    
    var body: some View {
        Text("\(updater.value)")
    }
}

然后在body中展示上面兩個(gè)View:

//直接可以使用let 
let updater = DelayUpdater()

var body: some View {
        VStack{
            ShowValueView().environmentObject(updater)
            BtnView().environmentObject(updater)
        }
    }

所以這兩個(gè)View通過(guò)去環(huán)境中拿數(shù)據(jù)展示,此處還可以將.environmentObject(updater)放到VStack后,效果一樣的,子視圖都需要updater。
完整代碼:

class DelayUpdater: ObservableObject {
    //@Published
    var value = 0 {
        willSet {
            //此處做另外的一些操作
            //前導(dǎo)的判斷
            //動(dòng)畫(huà)
            //調(diào)用其他方法
            objectWillChange.send()
        }
    }
    
    
    init() {
        for i in 1...10 {
            DispatchQueue.main.asyncAfter(deadline: .now() + Double(i)) {
                self.value += 1
            }
        }
    }
}

struct ShowValueView: View {
    
    @EnvironmentObject var updater: DelayUpdater
    
    var body: some View {
        Text("\(updater.value)")
    }
}

struct BtnView: View {
    @EnvironmentObject var updater: DelayUpdater
    
    var body: some View {
        Text("\(updater.value)")
    }
}

struct ContentView: View {
    let updater = DelayUpdater()
    var body: some View {
        VStack{
            ShowValueView().environmentObject(updater)
            BtnView().environmentObject(updater)
        }
    }
}
6、UIKit與SwiftUI交互

例如想在SwiftUI中使用UIKit中的一個(gè)視圖控制器,那么需要滿(mǎn)足怎樣的條件呢?
例如在一個(gè)SwiftUI項(xiàng)目中新建了一個(gè)Swift文件,新建一個(gè)UIViewController的子類(lèi),首先創(chuàng)建一個(gè)結(jié)構(gòu)體,讓此結(jié)構(gòu)體遵循UIViewControllerRepresentable協(xié)議:

class SubViewController : UIViewController  {   }

struct SubVC : UIViewControllerRepresentable { 
   func makeUIViewController (context: Context) -> SubViewController{
       return SubViewController()
    }
   func uodateUIViewController (_ uiviewController: SubViewController , context: Context) {}
}

如上SubViewController就可以在SwiftUI中正常使用了。

拓展:普通.swift類(lèi)型文件沒(méi)有預(yù)覽功能,而SwiftUI文件默認(rèn)自帶預(yù)覽功能。如果.swift類(lèi)型需要有預(yù)覽功能的話,可以模仿ContentView中的方法:

struct SubViewController_Previews: PreviewProvider {
    static var previews: some View {
        SubVC()
    }
}
7、ViewModifier

類(lèi)似于前端CSS視圖樣式,可以將控件的屬性包裝起來(lái),定義一次,全局不同子控件都能使用。

struct myModifier: ViewModifier {
    func body(content: Self.Content) -> some View {
        content.foregroundColor(.red).font(Font.system(size: 20, weight: .bold)).border(.green,width: 2)
    }
}
struct ContentView: View {
    let updater = DelayUpdater()
    var body: some View {
        VStack{
            Text("Hello Lcr").modifier(myModifier())
            Text("Hello Zf").modifier(myModifier())
        }
    }
}

這樣就可自定義多地方使用的ViewModifier,相同樣式的View就可以使用。

8、redacted

利用redacted可以給View添加一個(gè)類(lèi)似馬賽克的效果。默認(rèn)效果為.placeholder。

public enum RedactionReason {
    case placeh
    case black
    case blur
}

struct Placeholder: ViewModifier {
    func body(content: Content) -> some View {
        content.opacity(0)
            .overlay {
                RoundedRectangle(cornerRadius: 2)
                    .fill(.black.opacity(0.16))
            }
    }
}

struct BlackV: ViewModifier {
    func body(content: Content) -> some View {
        content.overlay(Color.black)
    }
}

struct Blurred: ViewModifier {
    func body(content: Content) -> some View {
        content.blur(radius: 4)
    }
}

struct Redactable: ViewModifier {
    let reason: RedactionReason?
    
    @ViewBuilder
    func body(content: Content) -> some View {
        switch reason {
        case .placeh:
            content.modifier(Placeholder())
        case .black:
            content.modifier(BlackV())
        case .blur:
            content.modifier(Blurred())
        case nil:
            content
        }
    }
}

extension View{
    func redacted(reason:RedactionReason?) -> some View{
        self.modifier(Redactable(reason: reason))
    }
}

struct ContentView: View {
    let updater = DelayUpdater()
    var body: some View {
        VStack{
            Text("Hello Lcr").padding()
                .redacted(reason: .blur)
            Text("Hello Zf")
        }
    }
}

利用.redacted(reason: .blur)就可切換不一樣的樣式。

redacted

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容