標籤:
UIActionSheet和UIAlertView都是ios系統內建的模態視圖,模態視圖的一個重要的特性就是在顯示模態視圖的時候可以阻斷其他視圖的事件響應。一般情況下我們對UIAlertView使用的比較多,UIActionSheet相對來說情況少一點,偶爾作為一個上拉菜單來展示還是非常有用的。通常如果顯示一個模態的視圖,可以自訂一個UIViewController,不過裡面的內容和動畫實現起來工作量還是非常多的。
UIActionSheet介紹
介紹UIActionSheet之前需要簡單的看下效果實現:
這是最基本的UIActionSheet,標題和按鈕,不過有的時候為了美觀可以不用標題,效果看起來是非常贊的,先上代碼之後講解:
UIActionSheet *actionSheet = [[UIActionSheet alloc] initWithTitle:@"部落格園" delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:@"確定" otherButtonTitles:@"keso", @"FlyElephant",nil]; actionSheet.actionSheetStyle = UIActionSheetStyleBlackOpaque; [actionSheet showInView:self.view];
大家可以明顯感覺到確定是白底紅字,其他的按鈕是白底藍字,因為確定在這裡是destructiveButton,相當於銷毀就是給使用者一個明顯的提示,這裡的顯示是直接在View中顯示,當然也有其他的地方顯示,調用方法如下:
- (void)showFromToolbar:(UIToolbar *)view;- (void)showFromTabBar:(UITabBar *)view;- (void)showFromBarButtonItem:(UIBarButtonItem *)item animated:(BOOL)animated NS_AVAILABLE_IOS(3_2);- (void)showFromRect:(CGRect)rect inView:(UIView *)view animated:(BOOL)animated NS_AVAILABLE_IOS(3_2);- (void)showInView:(UIView *)view;
跟大多數控制項一下,UIActionSheet也是有代理的,實現UIActionSheetDelegate可以在按鈕之後執行自己需要執行的事件:
-(void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex{ NSString *re[email protected]""; switch (buttonIndex) { case 0: [email protected]"確定"; break; case 1: [email protected]"keso"; break; case 2: [email protected]"FlyElephant"; break; case 3: [email protected]"取消"; break; } UIAlertView *alertView=[[UIAlertView alloc]initWithTitle:@"測試" message:result delegate:self cancelButtonTitle:@"確定" otherButtonTitles:nil]; [alertView show];}-(void)actionSheet:(UIActionSheet *)actionSheet didDismissWithButtonIndex:(NSInteger)buttonInde{ NSLog(@"didDismissWithButtonIndex-FlyElphant");}-(void)actionSheet:(UIActionSheet *)actionSheet willDismissWithButtonIndex:(NSInteger)buttonIndex{ NSLog(@"willDismissWithButtonIndex-FlyElphant");}-(void)actionSheetCancel:(UIActionSheet *)actionSheet{ NSLog(@"Home鍵執行此方法");}
四個方法都是比較常見的使用,一般情況下只需要調用第一個方法即可,actionSheetCancel網上說的比較少,這個方法一般是點擊Home鍵的時候執行,不是點擊取消的按鈕的執行,詳情可參考文檔解釋:
// Called when we cancel a view (eg. the user clicks the Home button). This is not called when the user clicks the cancel button.// If not defined in the delegate, we simulate a click in the cancel button
UIActionSheet的樣式預設樣式,黑色半透明和黑色不透明三種樣式:
typedef NS_ENUM(NSInteger, UIActionSheetStyle) { UIActionSheetStyleAutomatic = -1, // take appearance from toolbar style otherwise uses ‘default‘ UIActionSheetStyleDefault = UIBarStyleDefault, UIActionSheetStyleBlackTranslucent = UIBarStyleBlackTranslucent, UIActionSheetStyleBlackOpaque = UIBarStyleBlackOpaque,};
如果你覺得系統的不爽,可以自訂,完全取決於個人需求~
iOS開發-UIActionSheet簡單介紹