2.小部件开发的进阶之路

这个是产品要求的效果图

效果图.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("苹方-简 常规体", 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("苹方-简 常规体", 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("——网易云《我到外地去看你》").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("苹方-简 常规体", 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("苹方-简 常规体", 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))
    }
}

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 214,444评论 6 496
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 91,421评论 3 389
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 160,036评论 0 349
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 57,363评论 1 288
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 66,460评论 6 386
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 50,502评论 1 292
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 39,511评论 3 412
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 38,280评论 0 270
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 44,736评论 1 307
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,014评论 2 328
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,190评论 1 342
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 34,848评论 5 338
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 40,531评论 3 322
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,159评论 0 21
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,411评论 1 268
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 47,067评论 2 365
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,078评论 2 352