iOS开发之widget简单实现

结果图

IMG_0090.PNG

1.添加Today Extension

Paste_Image.png

添加后会有以下这部分内容(我的只是把MainInterface.storyboard删了)

Paste_Image.png

2.直接去plist文件填写相应的东西(这里NSExtensionPrincipalClass对应的TodayViewController是要和你的控制器名称一致)

Paste_Image.png

3.绘制相应的UI(注意:@"appextension://xxx",appextension是要和你项目中的URLSchemes Role添加一样的字段,后面xxx代表的是参数)

- (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调起app
    [self.extensionContext openURL:[NSURL URLWithString:@"appextension://xxx"] completionHandler:^(BOOL success) {
        NSLog(@"open url result:%d",success);
    }];

}

4.回到项目的delegate里面执行相应的操作

- (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) {
        //执行你要的操作
    }
    
    return YES;
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容