iOS的Widget類似Android的Notification設置flags為Notification.FLAG_ONGOING_EVENT后
OK,大約知道是什么意思了,現在可以開始碼了.
1.創建Widget
Xcode菜單 -> File -> New -> Target.. -> 選擇Today Extension
-->
2.在plist文件里設置純代碼的Widget
- 刪掉NSExtensionMainStoryboard字段
- 添加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博客園看到本文,請點擊查看原文.