iPhone – UIActionSheet Example

UIActionSheet is a cool way to get user input. The following example shows you how to implement the UIActionSheet.

1. Extend the UIActionSheetDelegate in the .h header file of the ViewController and add the(IBAction)showActionSheet:(id)sender method.

@interface MyViewController : UIViewController <UIActionSheetDelegate> {
	...
}

...

-(IBAction)showActionSheet:(id)sender;

@end

2. Add the following code in the .m implementation file. There are 5 parameters for initializing theUIActionSheet

  • initWithTitle:@”Title”
  • delegate:self
  • cancelButtonTitle:@”Cancel Button”
  • destructiveButtonTitle:@”Destructive Button”
  • otherButtonTitles:@”Other Button 1″, @”Other Button 2″, nil
-(IBAction)showActionSheet:(id)sender {
	UIActionSheet *popupQuery = [[UIActionSheet alloc] initWithTitle:@"Title" delegate:self cancelButtonTitle:@"Cancel Button" destructiveButtonTitle:@"Destructive Button" otherButtonTitles:@"Other Button 1", @"Other Button 2", nil];
	popupQuery.actionSheetStyle = UIActionSheetStyleBlackOpaque;
	[popupQuery showInView:self.view];
	[popupQuery release];
}

-(void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex {
	if (buttonIndex == 0) {
		self.label.text = @"Destructive Button Clicked";
	} else if (buttonIndex == 1) {
		self.label.text = @"Other Button 1 Clicked";
	} else if (buttonIndex == 2) {
		self.label.text = @"Other Button 2 Clicked";
	} else if (buttonIndex == 3) {
		self.label.text = @"Cancel Button Clicked";
	}

	/**
	 * OR use the following switch statement
	 * Suggested by Colin =)
	 */
	/*
	switch (buttonIndex) {
		case 0:
			self.label.text = @"Destructive Button Clicked";
			break;
		case 1:
			self.label.text = @"Other Button 1 Clicked";
			break;
		case 2:
			self.label.text = @"Other Button 2 Clicked";
			break;
		case 3:
			self.label.text = @"Cancel Button Clicked";
			break;
	}
	*/
}

3. Link the (IBAction)showActionSheet:(id)sender with a Hello Button in the main view such that the UIActionSheet will appear when user

 presses the Hello Button.

4. Text will be printed on the main view if u press the button in the UIActionSheet

帖上自己的代码

-(IBAction)shareBtn:(id)sender{
    
    UIActionSheet *actionSheet = [[UIActionSheet alloc] initWithTitle:@"分享到" delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"新浪微博",@"腾讯微博",@"短信",@"邮件",nil];
    actionSheet.actionSheetStyle = UIActionSheetStyleBlackOpaque;
    [actionSheet showInView:self.view];
    [actionSheet release];

}

- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex 
{ 
    switch (buttonIndex) {
		case 0:
			NSLog(@"新浪微博");
			break;
		case 1:
			NSLog(@"腾讯微博");
			break;
		case 2:
			NSLog(@"短信");
			break;
		case 3:
			NSLog(@"邮件");
			break;
	}
}


你可能感兴趣的:(iPhone – UIActionSheet Example)