iOS開發(fā)之widget簡單實現(xiàn)

結(jié)果圖

IMG_0090.PNG

1.添加Today Extension

Paste_Image.png

添加后會有以下這部分內(nèi)容(我的只是把MainInterface.storyboard刪了)

Paste_Image.png

2.直接去plist文件填寫相應(yīng)的東西(這里NSExtensionPrincipalClass對應(yīng)的TodayViewController是要和你的控制器名稱一致)

Paste_Image.png

3.繪制相應(yīng)的UI(注意:@"appextension://xxx",appextension是要和你項目中的URLSchemes Role添加一樣的字段,后面xxx代表的是參數(shù))

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.preferredContentSize = CGSizeMake([UIScreen mainScreen].bounds.size.width, 100);
    NSArray *dataArray = @[@"逛市場",@"消息", @"進貨車", @"我的"];
    NSArray *nImageArray = @[@"ico_toolbar_market",@"ico_toolbar_msg",@"ico_toolbar_cart", @"ico_toolbar_my"];
    
    for (int i = 0; i < 4; i++) {
        [self setupButtonWithTitle:dataArray[i] normalImage:nImageArray[i] leadI:i];
    }
}

- (void)setupButtonWithTitle:(NSString *)title normalImage:(NSString *)normalInage leadI:(int)i{

    CGFloat leadx =  i * (([UIScreen mainScreen].bounds.size.width-30)/4);
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    button.frame = CGRectMake(leadx+10, 45, ([UIScreen mainScreen].bounds.size.width-30)/4, 50);
    button.titleLabel.font = [UIFont systemFontOfSize:13];
    button.tag = i;
    [button setTitle:title forState:UIControlStateNormal];
    button.userInteractionEnabled = YES;
    button.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter;
    [button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [self.view addSubview:button];
    [button addTarget:self action:@selector(buttonClick:) forControlEvents:UIControlEventTouchUpInside];
    
    UIImageView *image = [[UIImageView alloc] initWithFrame:CGRectMake(leadx+10, 25, 30, 30)];
    image.image = [UIImage imageNamed:normalInage];
    image.center = CGPointMake(button.center.x, image.center.y);
    [image setContentMode:UIViewContentModeScaleAspectFit];
    [self.view addSubview:image];
    
}

- (void)buttonClick:(UIButton *)button {
    NSLog(@"%@",button);
    //通過extensionContext借助host app調(diào)起app
    [self.extensionContext openURL:[NSURL URLWithString:@"appextension://xxx"] completionHandler:^(BOOL success) {
        NSLog(@"open url result:%d",success);
    }];

}

4.回到項目的delegate里面執(zhí)行相應(yīng)的操作

- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation {
    
    debugMethod();
    debugLog(@"%@, %@", sourceApplication, url.host);
    
    if ([[url absoluteString] rangeOfString:@"appextension"].location != NSNotFound) {
        //執(zhí)行你要的操作
    }
    
    return YES;
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

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

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