雖然系統的AlertView(AlertController)已經非常簡單易用了,但偶爾還是想做些更酷炫的互動或者需要添加很多自定義的内容,這時候需要自定義個View來實作個性化的AlertView。
先來看看成品:
![](https://img.laitimes.com/img/9ZDMuAjOiMmIsIjOiQnIsIiNwUTO1kTN1EDOyIDM2EDMy8CX0Vmbu4GZzNmLn9Gbi1yZtl2Lc9CX6MHc0RHaiojIsJye.jpg)
代碼非常少,但效果十分出衆。
首先我用xib建立了需要自定義的提示視圖,建立好限制
建立對應的類我這裡就叫MyAlertView
之後outlet中心需要動畫的view,這裡叫做centerView
@property (weak, nonatomic) IBOutlet UIView *centerView;
在自定義類MyAlertView中充寫awakefromnib方法實作動畫,并實作退出按鈕的反向動畫
- (void)awakeFromNib{
self.centerView.transform = CGAffineTransformMakeScale(, );
self.backgroundColor = [UIColor colorWithRed: green: blue: alpha:];
[UIView animateWithDuration: delay: usingSpringWithDamping: initialSpringVelocity: options:UIViewAnimationOptionCurveEaseIn animations:^{
self.centerView.transform = CGAffineTransformMakeScale(, );
self.backgroundColor = [UIColor colorWithRed: green: blue: alpha:];
} completion:^(BOOL finished) {
}];
}
- (IBAction)quit:(id)sender {
[UIView animateWithDuration: delay: usingSpringWithDamping: initialSpringVelocity: options:UIViewAnimationOptionCurveEaseIn animations:^{
self.backgroundColor = [UIColor colorWithRed: green: blue: alpha:];
self.centerView.transform = CGAffineTransformMakeScale(, );
} completion:^(BOOL finished) {
[self removeFromSuperview];
}];
}
最後在主要制器中建立自定義的“AlertView”,并展現出來
- (IBAction)showAlert:(id)sender{
MyAlertView *alert = [[NSBundle mainBundle] loadNibNamed:@"MyAlertView" owner:nil options:nil][];
alert.frame = self.view.bounds;
[self.view addSubview:alert];
}
十分簡單,但有一點需要注意最後移除view的動畫設定縮放參數的時候不可以設定為0,否則動畫不會顯示,這裡用了級小值0.0001來近似0的效果。
最後,用自定義view來實作雖然可以奏效,但反觀蘋果在iOS8中用AlertContrller來代替AlertView,這種模态視圖用控制器來管理結構才是比較清晰的,是以這裡可以用自定義控制器來實作同樣功能,模态彈出的時候presentation的方式需要設定為Over Current Contxt就可以了。