iOS Widget简单使用

iOS的Widget类似Android的Notification设置flags为Notification.FLAG_ONGOING_EVENT后

    

 

OK,大约知道是什么意思了,现在可以开始码了.

1.创建Widget

Xcode菜单 -> File -> New -> Target.. -> 选择Today Extension

  --> 

 

2.在plist文件里设置纯代码的Widget

  1. 删掉NSExtensionMainStoryboard字段
  2. 添加NSExtensionPrincipalClass字段,设置value为TodayViewController,当然也可以设置其他的ViewController

 

3.运行的时候选择Today

 

4.添加一些控件看看效果

复制代码
- (void)viewDidLoad {
    [super viewDidLoad];
    //  设置widget的高度
    self.preferredContentSize = CGSizeMake(self.view.bounds.size.width, 100);
    //  添加一个button,点击button后改变背景的颜色
    UIButton *button = [UIButton buttonWithType:UIButtonTypeSystem];
    [button setTitle:@"点击一下" forState:UIControlStateNormal];
    button.backgroundColor = [UIColor whiteColor];
    [button addTarget:self action:@selector(clickAction) forControlEvents:UIControlEventTouchUpInside];
    button.frame = CGRectMake(50, 10, 100, 30);
    [self.view addSubview:button];
    
}

- (void)clickAction{
    self.view.backgroundColor = [UIColor redColor];
}
复制代码

 

效果如图

 

看效果图你会发现,左边还空了一大块,原因是Widget默认会有一个inset,重写下面的方法就好了

-(UIEdgeInsets)widgetMarginInsetsForProposedMarginInsets:(UIEdgeInsets)defaultMarginInsets {
    return UIEdgeInsetsZero;
}

最终的效果如下:

 

如果你不是在wb145230博客园看到本文,请点击查看原文.

 

posted @   wb145230  阅读(2253)  评论(2编辑  收藏  举报
编辑推荐:
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 展开说说关于C#中ORM框架的用法!
点击右上角即可分享
微信分享提示