2.小部件開發(fā)的進階之路

這個是產(chǎn)品要求的效果圖

效果圖.png

廢話不多說,直接上代碼借浊,通過代碼一步步的對小組件進行更深的了解和體會

//
//  ClockTwoWidget.swift
//  ClockTwoWidget
//
//  Created by Bron on 2020/9/26.
//

import WidgetKit
import SwiftUI
import YYCategories
import SwiftDate

struct TwoProvider: TimelineProvider {
    func placeholder(in context: Context) -> TwoSimpleEntry {
//        let currentDate = Date().addingTimeInterval(8*60*60)
        let model = self.getModel()
        return TwoSimpleEntry(date: Date(), model: model)
    }

    func getSnapshot(in context: Context, completion: @escaping (TwoSimpleEntry) -> ()) {

        let model = self.getModel()
        let entry = TwoSimpleEntry(date: Date(), model: model)
        completion(entry)
    }

    func getTimeline(in context: Context, completion: @escaping (Timeline<Entry>) -> ()) {
        var entries: [TwoSimpleEntry] = []
        // Generate a timeline consisting of five entries an hour apart, starting from the current date.
        for secondOffset in 0 ..< 2 {
            let currentDate = Date()
            let model = self.getModel()
            let entryDate = Calendar.current.date(byAdding: .minute, value: secondOffset, to: currentDate)!
            let entry = TwoSimpleEntry(date: entryDate,model: model)
            entries.append(entry)
        }
        
        let timeline = Timeline(entries: entries, policy: .atEnd)
        completion(timeline)
    }
    func getModel()->Model{
       let currentDate = Date().addingTimeInterval(8*60*60)
        let hour = currentDate.toFormat("HH")
        let hourTime = Int(hour) ?? 0
        let hourTimeStr =  hourTime  > 12 ? hourTime - 12 : hourTime
        let ampmStr = hourTime  > 12 ? "PM" : "AM"
        let sharedDefaults  = UserDefaults(suiteName: "group.com.XXXX.XXXX")
        let imgBase64Str = sharedDefaults?.value(forKey: "smallClock2bgImage") as? String ?? ""
        let decodeImageData = NSData(base64Encoded: imgBase64Str, options: NSData.Base64DecodingOptions.ignoreUnknownCharacters)
        let decodeImage = UIImage(data: decodeImageData as! Data) ?? UIImage()
        let bgImage = Image.init(uiImage: decodeImage)
        let bgColorStr = sharedDefaults?.value(forKey: "smallClock2Color") as? String ?? "#D9DEED"
        let week =  currentDate.weekday
        
        //middleWidget
        let middlebgColorStr = sharedDefaults?.value(forKey: "middleClock2Color") as? String ?? "#D9DEED"
        let middleimgBase64Str = sharedDefaults?.value(forKey: "middleClock2bgImage") as? String ?? ""
        let middledecodeImageData = NSData(base64Encoded: middleimgBase64Str, options: NSData.Base64DecodingOptions.ignoreUnknownCharacters)
        let middledecodeImage = UIImage(data: middledecodeImageData as! Data) ?? UIImage()
        let middlebgImage  = Image.init(uiImage: middledecodeImage)

        //large
        let largebgColorStr = sharedDefaults?.value(forKey: "largeClock2Color") as? String ?? "#D9DEED"
        let largeimgBase64Str = sharedDefaults?.value(forKey: "largeClock2bgImage") as? String ?? ""
        let largedecodeImageData = NSData(base64Encoded: largeimgBase64Str, options: NSData.Base64DecodingOptions.ignoreUnknownCharacters)
        let largedecodeImage = UIImage(data: largedecodeImageData as! Data) ?? UIImage()
        let largebgImage  = Image.init(uiImage: largedecodeImage)

        let model = Model(bgImage: bgImage, amPmStr: ampmStr, weekIndex: week, isImgBg: false ,hourTimeStr: "\(hourTimeStr)",bgImageColorStr: bgColorStr, middlebgImage: middlebgImage, middlebgImageColorStr: middlebgColorStr, currentDate: currentDate,largebgImage: largebgImage,largebgImageColorStr: largebgColorStr)
       return model
    }
}

struct Model {
    let bgImage:Image
    let amPmStr: String
    let weekIndex: Int
    let isImgBg: Bool
    let hourTimeStr:String
    let bgImageColorStr:String
    let middlebgImage:Image
    let middlebgImageColorStr:String
    let currentDate: Date
    let largebgImage:Image
    let largebgImageColorStr:String

}

struct ClockTwoWidgetEntryView : View {
    @Environment(\.widgetFamily) var yfamily: WidgetFamily
    var entry: TwoProvider.Entry

    var body: some View {
        if yfamily == .systemSmall {
                VStack(alignment: .center, spacing: 30.0, content: {
                    Group {
                        Text("\(entry.date.toFormat("yyyy-MM-dd"))").frame(width: 95, height: 20, alignment: .center).foregroundColor(.black).font(Font.custom("蘋方-簡 常規(guī)體", size: 13))
                    }
                    .background(Color.init(UIColor(hexString: "#FFFFFF")?.withAlphaComponent(0.5) ?? UIColor.init()))
                    .cornerRadius(5).offset(CGSize(width: 0.0, height: 30.0))
                    HStack(alignment: /*@START_MENU_TOKEN@*/.center/*@END_MENU_TOKEN@*/, spacing: 10, content: {
                        Text("\(entry.model.currentDate.toFormat("HH"))").font(Font.custom("zcool-gdh", size: 32)).frame(width: 55, height: 70, alignment: /*@START_MENU_TOKEN@*/.center/*@END_MENU_TOKEN@*/).background(Color.init(UIColor(hexString: "#FFFFFF")?.withAlphaComponent(0.6) ?? UIColor())).cornerRadius(10)
                        Text(":").font(Font.custom("蘋方-簡 中粗體", size: 32))
                        Text("\(entry.model.currentDate.toFormat("mm"))").font(Font.custom("zcool-gdh", size: 32)).frame(width: 55, height: 70, alignment: /*@START_MENU_TOKEN@*/.center/*@END_MENU_TOKEN@*/).background(Color.init(UIColor(hexString: "#FFFFFF")?.withAlphaComponent(0.6) ?? UIColor())).cornerRadius(10)
                    }).foregroundColor(.black).offset(CGSize(width: 0.0, height: 10.0))
                    HStack(alignment: /*@START_MENU_TOKEN@*/.center/*@END_MENU_TOKEN@*/, spacing: 0, content: {
                        HStack{
                            Text("一").frame(width: 13, height: 20, alignment: /*@START_MENU_TOKEN@*/.center/*@END_MENU_TOKEN@*/).foregroundColor(Color(UIColor(hexString: "#000000")?.withAlphaComponent(entry.model.weekIndex == 2 ? 1.0 : 0.2) ?? UIColor()))
                            Text("二").frame(width: 13, height: 20, alignment: /*@START_MENU_TOKEN@*/.center/*@END_MENU_TOKEN@*/).foregroundColor(Color(UIColor(hexString: "#000000")?.withAlphaComponent(entry.model.weekIndex == 3 ? 1.0 : 0.2) ?? UIColor()))
                            Text("三").frame(width: 13, height: 20, alignment: /*@START_MENU_TOKEN@*/.center/*@END_MENU_TOKEN@*/).foregroundColor(Color(UIColor(hexString: "#000000")?.withAlphaComponent(entry.model.weekIndex == 4 ? 1.0 : 0.2) ?? UIColor()))
                            Text("四").frame(width: 13, height: 20, alignment: /*@START_MENU_TOKEN@*/.center/*@END_MENU_TOKEN@*/).foregroundColor(Color(UIColor(hexString: "#000000")?.withAlphaComponent(entry.model.weekIndex == 5 ? 1.0 : 0.2) ?? UIColor()))
                            Text("五").frame(width: 13, height: 20, alignment: /*@START_MENU_TOKEN@*/.center/*@END_MENU_TOKEN@*/).foregroundColor(Color(UIColor(hexString: "#000000")?.withAlphaComponent(entry.model.weekIndex == 6 ? 1.0 : 0.2) ?? UIColor()))
                            Text("六").frame(width: 13, height: 20, alignment: /*@START_MENU_TOKEN@*/.center/*@END_MENU_TOKEN@*/).foregroundColor(Color(UIColor(hexString: "#000000")?.withAlphaComponent(entry.model.weekIndex == 7 ? 1.0 : 0.2) ?? UIColor()))
                            Text("日").frame(width: 13, height: 20, alignment: /*@START_MENU_TOKEN@*/.center/*@END_MENU_TOKEN@*/).foregroundColor(Color(UIColor(hexString: "#000000")?.withAlphaComponent(entry.model.weekIndex == 1 ? 1.0 : 0.2) ?? UIColor()))
                        }.font(Font.custom("蘋方-簡 常規(guī)體", size: 12)).background(Color.init(UIColor(hexString: "#FFFFFF")?.withAlphaComponent(0.5) ?? UIColor())).cornerRadius(5)
                    }).frame(minWidth: /*@START_MENU_TOKEN@*/0/*@END_MENU_TOKEN@*/, idealWidth: 0, maxWidth: /*@START_MENU_TOKEN@*/.infinity/*@END_MENU_TOKEN@*/, minHeight: /*@START_MENU_TOKEN@*/0/*@END_MENU_TOKEN@*/, idealHeight: 0, maxHeight: /*@START_MENU_TOKEN@*/.infinity/*@END_MENU_TOKEN@*/, alignment: /*@START_MENU_TOKEN@*/.center/*@END_MENU_TOKEN@*/)
                    Spacer()
                }).background(entry.model.bgImage.resizable()).background(Color(UIColor(hexString: entry.model.bgImageColorStr) ?? UIColor())).widgetURL(URL(string: "Clock-small-2/https://www.baidu.com/small"))

        }
        if yfamily == .systemMedium {
            Link(destination: URL(string: "Clock-meduim-2/https://www.baidu.com/medium/1")!) {
                VStack(alignment: /*@START_MENU_TOKEN@*/.center/*@END_MENU_TOKEN@*/, spacing: /*@START_MENU_TOKEN@*/nil/*@END_MENU_TOKEN@*/, content: {
                    HStack(alignment: /*@START_MENU_TOKEN@*/.center/*@END_MENU_TOKEN@*/, spacing: nil, content: {
                        Text("\(entry.model.hourTimeStr)").font(Font.custom("zihun64hao-mengquruantangti", size: 100))
                        Text(":").font(Font.custom("zihun64hao-mengquruantangti", size: 100))
                        Text("\(entry.date.toFormat("mm"))").font(Font.custom("zihun64hao-mengquruantangti", size: 100))
                    }).foregroundColor(.white).offset(x: 0, y: 5)
                    HStack(alignment: /*@START_MENU_TOKEN@*/.center/*@END_MENU_TOKEN@*/, spacing: /*@START_MENU_TOKEN@*/nil/*@END_MENU_TOKEN@*/, content: {
                        Spacer()
                    })
                    Text("祝你們幸福是假的拴竹,祝你幸福是真的扫俺。").font(Font.custom("zihun64hao-mengquruantangti", size: 14)).foregroundColor(.white).offset(x: 10, y: -10.0/*@END_MENU_TOKEN@*/)
                    Text("——網(wǎng)易云《我到外地去看你》").font(Font.custom("zihun64hao-mengquruantangti", size: 14)).foregroundColor(.white).offset(x: 30, y: -10.0/*@END_MENU_TOKEN@*/)
                    
                    Spacer()
                }).background(entry.model.middlebgImage.resizable()).background(Color(UIColor(hexString: entry.model.middlebgImageColorStr) ?? UIColor()))
            }

        }
        if yfamily == .systemLarge {
            Link(destination: URL(string: "Clock-large-2/https://www.baidu.com/large/1")!) {
                VStack(alignment: .center, spacing: 30.0, content: {
                    Group {
                        Text("\(entry.date.toFormat("yyyy-MM-dd"))").frame(width: 300, height: 50, alignment: .center).foregroundColor(.black).font(Font.custom("蘋方-簡 常規(guī)體", size: 20))
                    }
                    .background(Color.init(UIColor(hexString: "#FFFFFF")?.withAlphaComponent(0.5) ?? UIColor.init()))
                    .cornerRadius(10).offset(CGSize(width: 0.0, height: 20.0))
                    HStack(alignment: /*@START_MENU_TOKEN@*/.center/*@END_MENU_TOKEN@*/, spacing: 10, content: {
                        Text("\(entry.model.currentDate.toFormat("HH"))").font(Font.custom("zcool-gdh", size: 77)).frame(width: 130, height: 175,alignment: .center).background(Color.init(UIColor(hexString: "#FFFFFF")?.withAlphaComponent(0.6) ?? UIColor())).cornerRadius(10)
                        Text(":").font(Font.custom("蘋方-簡 中粗體", size: 77))
                        Text("\(entry.model.currentDate.toFormat("mm"))").font(Font.custom("zcool-gdh", size: 77)).frame(width: 130, height: 175, alignment: /*@START_MENU_TOKEN@*/.center/*@END_MENU_TOKEN@*/).background(Color.init(UIColor(hexString: "#FFFFFF")?.withAlphaComponent(0.6) ?? UIColor())).cornerRadius(10)
                    }).foregroundColor(.black).offset(CGSize(width: 0.0, height: 10.0))
                    HStack(alignment: /*@START_MENU_TOKEN@*/.center/*@END_MENU_TOKEN@*/, spacing: 0, content: {
                        HStack{
                            Text("").frame(width: -1, height: 30, alignment: .center)
                            Text("一").frame(width: 34, height: 40, alignment: /*@START_MENU_TOKEN@*/.center/*@END_MENU_TOKEN@*/).foregroundColor(Color(UIColor(hexString: "#000000")?.withAlphaComponent(entry.model.weekIndex == 2 ? 1.0 : 0.2) ?? UIColor()))
                            Text("二").frame(width: 34, height: 27, alignment: /*@START_MENU_TOKEN@*/.center/*@END_MENU_TOKEN@*/).foregroundColor(Color(UIColor(hexString: "#000000")?.withAlphaComponent(entry.model.weekIndex == 3 ? 1.0 : 0.2) ?? UIColor()))
                            Text("三").frame(width: 34, height: 27, alignment: /*@START_MENU_TOKEN@*/.center/*@END_MENU_TOKEN@*/).foregroundColor(Color(UIColor(hexString: "#000000")?.withAlphaComponent(entry.model.weekIndex == 4 ? 1.0 : 0.2) ?? UIColor()))
                            Text("四").frame(width: 34, height: 27, alignment: /*@START_MENU_TOKEN@*/.center/*@END_MENU_TOKEN@*/).foregroundColor(Color(UIColor(hexString: "#000000")?.withAlphaComponent(entry.model.weekIndex == 5 ? 1.0 : 0.2) ?? UIColor()))
                            Text("五").frame(width: 34, height: 27, alignment: /*@START_MENU_TOKEN@*/.center/*@END_MENU_TOKEN@*/).foregroundColor(Color(UIColor(hexString: "#000000")?.withAlphaComponent(entry.model.weekIndex == 6 ? 1.0 : 0.2) ?? UIColor()))
                            Text("六").frame(width: 34, height: 27, alignment: /*@START_MENU_TOKEN@*/.center/*@END_MENU_TOKEN@*/).foregroundColor(Color(UIColor(hexString: "#000000")?.withAlphaComponent(entry.model.weekIndex == 7 ? 1.0 : 0.2) ?? UIColor()))
                            Text("日").frame(width: 34, height: 27, alignment: .center).foregroundColor(Color(UIColor(hexString: "#000000")?.withAlphaComponent(entry.model.weekIndex == 1 ? 1.0 : 0.2) ?? UIColor()))
                            Text("").frame(width: -1, height: 30, alignment: .center)
                        }.font(Font.custom("蘋方-簡 常規(guī)體", size: 12)).background(Color.init(UIColor(hexString: "#FFFFFF")?.withAlphaComponent(0.5) ?? UIColor())).cornerRadius(5)
                    }).frame(minWidth: /*@START_MENU_TOKEN@*/0/*@END_MENU_TOKEN@*/, idealWidth: 0, maxWidth: /*@START_MENU_TOKEN@*/.infinity/*@END_MENU_TOKEN@*/, minHeight: /*@START_MENU_TOKEN@*/0/*@END_MENU_TOKEN@*/, idealHeight: 0, maxHeight: /*@START_MENU_TOKEN@*/.infinity/*@END_MENU_TOKEN@*/, alignment: /*@START_MENU_TOKEN@*/.center/*@END_MENU_TOKEN@*/).offset(x: 0, y: /*@START_MENU_TOKEN@*/10.0/*@END_MENU_TOKEN@*/)
                    Spacer()
                }).background(entry.model.largebgImage.resizable()).background(Color(UIColor(hexString: entry.model.largebgImageColorStr) ?? UIColor()))
            }

        }
    }
}


@main
struct ClockTwoWidget: Widget {
    let kind: String = "ClockTwoWidget"

    var body: some WidgetConfiguration {
        StaticConfiguration(kind: kind, provider: TwoProvider()) { entry in
            ClockTwoWidgetEntryView(entry: entry)
        }
        .configurationDisplayName("ClockTwoWidget")
        .description("This is an example widget.")
    }
}

struct ClockTwoWidget_Previews: PreviewProvider {
    static var previews: some View {
        ClockTwoWidgetEntryView(entry: TwoSimpleEntry(date: Date().addingTimeInterval(8*60*60),model: Model(bgImage: Image(""), amPmStr: "PM", weekIndex: 2, isImgBg: false ,hourTimeStr: "04",bgImageColorStr: "#D9DEED", middlebgImage: Image(""), middlebgImageColorStr: "#D9DEED", currentDate: Date(),largebgImage: Image(""),largebgImageColorStr: "#D9DEED")))
            .previewContext(WidgetPreviewContext(family: .systemSmall))
        ClockTwoWidgetEntryView(entry: TwoSimpleEntry(date: Date().addingTimeInterval(8*60*60),model: Model(bgImage: Image(""), amPmStr: "PM", weekIndex: 2, isImgBg: false ,hourTimeStr: "04",bgImageColorStr: "#D9DEED", middlebgImage: Image(""), middlebgImageColorStr: "#D9DEED", currentDate: Date(),largebgImage: Image(""),largebgImageColorStr: "#D9DEED")))
            .previewContext(WidgetPreviewContext(family: .systemMedium))
        ClockTwoWidgetEntryView(entry: TwoSimpleEntry(date: Date().addingTimeInterval(8*60*60),model: Model(bgImage: Image(""), amPmStr: "PM", weekIndex: 1, isImgBg: false ,hourTimeStr: "04",bgImageColorStr: "#D9DEED", middlebgImage: Image(""), middlebgImageColorStr: "#D9DEED", currentDate: Date(),largebgImage: Image(""),largebgImageColorStr: "#D9DEED")))
            .previewContext(WidgetPreviewContext(family: .systemLarge))
    }
}

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末路鹰,一起剝皮案震驚了整個濱河市惨篱,隨后出現(xiàn)的幾起案子盏筐,更是在濱河造成了極大的恐慌,老刑警劉巖砸讳,帶你破解...
    沈念sama閱讀 212,185評論 6 493
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件琢融,死亡現(xiàn)場離奇詭異,居然都是意外死亡绣夺,警方通過查閱死者的電腦和手機吏奸,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 90,445評論 3 385
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來陶耍,“玉大人奋蔚,你說我怎么就攤上這事×页” “怎么了泊碑?”我有些...
    開封第一講書人閱讀 157,684評論 0 348
  • 文/不壞的土叔 我叫張陵,是天一觀的道長毯欣。 經(jīng)常有香客問我馒过,道長,這世上最難降的妖魔是什么酗钞? 我笑而不...
    開封第一講書人閱讀 56,564評論 1 284
  • 正文 為了忘掉前任腹忽,我火速辦了婚禮,結(jié)果婚禮上砚作,老公的妹妹穿的比我還像新娘窘奏。我一直安慰自己,他們只是感情好葫录,可當我...
    茶點故事閱讀 65,681評論 6 386
  • 文/花漫 我一把揭開白布着裹。 她就那樣靜靜地躺著,像睡著了一般米同。 火紅的嫁衣襯著肌膚如雪骇扇。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 49,874評論 1 290
  • 那天面粮,我揣著相機與錄音少孝,去河邊找鬼。 笑死熬苍,一個胖子當著我的面吹牛韭山,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 39,025評論 3 408
  • 文/蒼蘭香墨 我猛地睜開眼钱磅,長吁一口氣:“原來是場噩夢啊……” “哼梦裂!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起盖淡,我...
    開封第一講書人閱讀 37,761評論 0 268
  • 序言:老撾萬榮一對情侶失蹤年柠,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后褪迟,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體冗恨,經(jīng)...
    沈念sama閱讀 44,217評論 1 303
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 36,545評論 2 327
  • 正文 我和宋清朗相戀三年味赃,在試婚紗的時候發(fā)現(xiàn)自己被綠了掀抹。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 38,694評論 1 341
  • 序言:一個原本活蹦亂跳的男人離奇死亡心俗,死狀恐怖傲武,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情城榛,我是刑警寧澤揪利,帶...
    沈念sama閱讀 34,351評論 4 332
  • 正文 年R本政府宣布,位于F島的核電站狠持,受9級特大地震影響疟位,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜喘垂,卻給世界環(huán)境...
    茶點故事閱讀 39,988評論 3 315
  • 文/蒙蒙 一甜刻、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧正勒,春花似錦得院、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 30,778評論 0 21
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽矾柜。三九已至阱驾,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間怪蔑,已是汗流浹背里覆。 一陣腳步聲響...
    開封第一講書人閱讀 32,007評論 1 266
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留缆瓣,地道東北人喧枷。 一個月前我還...
    沈念sama閱讀 46,427評論 2 360
  • 正文 我出身青樓,卻偏偏與公主長得像,于是被迫代替她去往敵國和親隧甚。 傳聞我的和親對象是個殘疾皇子车荔,可洞房花燭夜當晚...
    茶點故事閱讀 43,580評論 2 349