添加UIPickerView&一个按钮在行动表 - 如何?

时间:2009-08-11 20:01:11

标签: ios iphone uipickerview actionsheetpicker

我的申请需要在行动表中添加以下内容。

  • UIToolbar
  • UIToolbar上的按钮
  • UIPicker Control

我已经包含了一张图片来了解我的要求。

alt text

请您解释一下,如何实施?

11 个答案:

答案 0 :(得分:111)

还有一个解决方案:

  • 没有工具栏,只有分段控件(eyecandy)

    UIActionSheet *actionSheet = [[UIActionSheet alloc] initWithTitle:nil 
                                                        delegate:nil
                                                        cancelButtonTitle:nil
                                                        destructiveButtonTitle:nil
                                                        otherButtonTitles:nil];
    
    [actionSheet setActionSheetStyle:UIActionSheetStyleBlackTranslucent];
    
    CGRect pickerFrame = CGRectMake(0, 40, 0, 0);
    
    UIPickerView *pickerView = [[UIPickerView alloc] initWithFrame:pickerFrame];
    pickerView.showsSelectionIndicator = YES;
    pickerView.dataSource = self;
    pickerView.delegate = self;
    
    [actionSheet addSubview:pickerView];
    [pickerView release];
    
    UISegmentedControl *closeButton = [[UISegmentedControl alloc] initWithItems:[NSArray arrayWithObject:@"Close"]];
    closeButton.momentary = YES; 
    closeButton.frame = CGRectMake(260, 7.0f, 50.0f, 30.0f);
    closeButton.segmentedControlStyle = UISegmentedControlStyleBar;
    closeButton.tintColor = [UIColor blackColor];
    [closeButton addTarget:self action:@selector(dismissActionSheet:) forControlEvents:UIControlEventValueChanged];
    [actionSheet addSubview:closeButton];
    [closeButton release];
    
    [actionSheet showInView:[[UIApplication sharedApplication] keyWindow]];
    
    [actionSheet setBounds:CGRectMake(0, 0, 320, 485)];
    

答案 1 :(得分:75)

即使这个问题很老,我也会很快提到我已经将ActionSheetPicker class与一个便利函数放在一起,因此您可以在一行中生成一个带有UIPickerView的ActionSheet。它基于此问题答案的代码。

编辑:现在它还支持使用DatePicker和DistancePicker。


UPD:

不推荐使用此版本:改为使用ActionSheetPicker-3.0

animation

答案 2 :(得分:32)

是的!我终于找到了它。

在按钮点击事件上实现以下代码,以弹出问题图像中给出的操作表。

UIActionSheet *aac = [[UIActionSheet alloc] initWithTitle:@"How many?"
                                             delegate:self
                                    cancelButtonTitle:nil
                               destructiveButtonTitle:nil
                                    otherButtonTitles:nil];

UIDatePicker *theDatePicker = [[UIDatePicker alloc] initWithFrame:CGRectMake(0.0, 44.0, 0.0, 0.0)];
if(IsDateSelected==YES)
{
    theDatePicker.datePickerMode = UIDatePickerModeDate;
    theDatePicker.maximumDate=[NSDate date];
}else {
    theDatePicker.datePickerMode = UIDatePickerModeTime;
}

self.dtpicker = theDatePicker;
[theDatePicker release];
[dtpicker addTarget:self action:@selector(dateChanged) forControlEvents:UIControlEventValueChanged];

pickerDateToolbar = [[UIToolbar alloc] initWithFrame:CGRectMake(0, 0, 320, 44)];
pickerDateToolbar.barStyle = UIBarStyleBlackOpaque;
[pickerDateToolbar sizeToFit];

NSMutableArray *barItems = [[NSMutableArray alloc] init];

UIBarButtonItem *flexSpace = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:self action:nil];
[barItems addObject:flexSpace];

UIBarButtonItem *doneBtn = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone target:self action:@selector(DatePickerDoneClick)];
[barItems addObject:doneBtn];

[pickerDateToolbar setItems:barItems animated:YES];

[aac addSubview:pickerDateToolbar];
[aac addSubview:dtpicker];
[aac showInView:self.view];
[aac setBounds:CGRectMake(0,0,320, 464)];

答案 3 :(得分:25)

iOS 7更新

Apple docs for UIActionSheetUIActionSheet is not designed to be subclassed, nor should you add views to its hierarchy

我建议不要尝试自定义ActionSheet的内容,因为它可能会导致iOS 7中出现严重的无效上下文错误。我只花了几个小时来解决这个问题,最终决定采取不同的方法。我用一个包含简单tableview的模态视图控制器替换了调用以显示操作表。

有很多方法可以实现这一目标。这是我刚刚在当前项目中实现的一种方式。这很好,因为我可以在5到6个不同的屏幕之间重复使用它,我所有用户都可以从选项列表中进行选择。

  1. 创建一个新的UITableViewController子类SimpleTableViewController
  2. 在故事板中创建一个UITableViewController(嵌入在导航控制器中)并将其自定义类设置为SimpleTableViewController。
  3. 为SimpleTableViewController的导航控制器提供故事板ID“SimpleTableVC”。
  4. 在SimpleTableViewController.h中,创建一个NSArray属性,该属性将表示表中的数据。
  5. 同样在SimpleTableViewController.h中,使用必需的方法SimpleTableViewControllerDelegate创建协议itemSelectedatRow:,并使用类型为id<SimpleTableViewControllerDelegate>的委托创建弱属性。这就是我们将选择传递回父控制器的方式。
  6. 在SimpleTableViewController.m中,实现tableview数据源和委托方法,在itemSelectedatRow:中调用tableView:didSelectRowAtIndexPath:
  7. 这种方法具有可公平重用的额外好处。要使用,请在ViewController.h中导入SimpleTableViewController类,符合SimpleTableViewDelegate,并实现itemSelectedAtRow:方法。然后,打开模态只是实例化一个新的SimpleTableViewController,设置表数据和委托,并呈现它。

    UINavigationController *navigationController = (UINavigationController *)[self.storyboard instantiateViewControllerWithIdentifier:@"SimpleTableVC"];
    SimpleTableViewController *tableViewController = (SimpleTableViewController *)[[navigationController viewControllers] objectAtIndex:0];
    tableViewController.tableData = self.statesArray;
    tableViewController.navigationItem.title = @"States";
    tableViewController.delegate = self;
    [self presentViewController:navigationController animated:YES completion:nil];
    

    我创建了一个简单的示例posted it on github

    另见Showing actionsheet causes CGContext invalid context errors

答案 4 :(得分:10)

Marcio对这个问题的出色解决方案对我在UIActionSheet中添加任何类型的子视图非常有帮助。

由于我尚未完全清楚的原因,UIActionSheet的界限只能在显示之后设置; sagar和marcio的解决方案都成功地通过setBounds:CGRectMake(...)消息发送到后显示

但是,在显示工作表之后设置UIActionSheet边界会在ActionSheet显示时创建一个跳转过渡,它会“弹出”到视图中,然后仅滚动到最后40个像素左右。

在添加子视图后调整UIPickerView的大小时,我建议将发送到动画块内的actionSheet的setBounds消息包装起来。这将使actionSheet的入口显得更加平滑。

UIActionSheet *actionSheet = [[[UIActionSheet alloc] initWithTitle:nil delegate:nil cancelButtonTitle:nil destructiveButtonTitle:nil otherButtonTitles:nil];


// add one or more subviews to the UIActionSheet
// this could be a UIPickerView, or UISegmentedControl buttons, or any other 
// UIView.  Here, let's just assume it's already set up and is called 
// (UIView *)mySubView
[actionSheet addSubview:myView];

// show the actionSheet
[actionSheet showInView:[UIApplication mainWindow]];


// Size the actionSheet with smooth animation
    [UIView beginAnimations:nil context:nil];
    [actionSheet setBounds:CGRectMake(0, 0, 320, 485)];
    [UIView commitAnimations]; 

答案 5 :(得分:9)

对于那些想要找到DatePickerDoneClick函数的人来说......这里是解雇Action Sheet的简单代码。显然,aac应该是一个ivar(你的implmentation .h文件中的那个)


- (void)DatePickerDoneClick:(id)sender{
    [aac dismissWithClickedButtonIndex:0 animated:YES];
}

答案 6 :(得分:9)

我真的不明白为什么UIPickerView会进入UIActionSheet。这似乎是一个混乱和hacky解决方案,可以在未来的iOS版本中打破。 (我之前在应用程序中有过这样的内容,第一次点击时没有显示UIPickerView并且必须被重新显示 - UIActionSheet的奇怪怪癖。

我所做的只是实现一个UIPickerView,然后将其作为子视图添加到我的视图中,并将其设置为向上移动,就好像它像活动表一样呈现。

/// Add the PickerView as a private variable
@interface EMYourClassName ()

@property (nonatomic, strong) UIPickerView *picker;
@property (nonatomic, strong) UIButton *backgroundTapButton;

@end

///
/// This is your action which will present the picker view
///
- (IBAction)showPickerView:(id)sender {

    // Uses the default UIPickerView frame.
    self.picker = [[UIPickerView alloc] initWithFrame:CGRectZero];

    // Place the Pickerview off the bottom of the screen, in the middle set the datasource delegate and indicator
    _picker.center = CGPointMake([[UIScreen mainScreen] bounds].size.width / 2.0, [[UIScreen mainScreen] bounds].size.height + _picker.frame.size.height);
    _picker.dataSource = self;
    _picker.delegate = self;
    _picker.showsSelectionIndicator = YES;

    // Create the toolbar and place it at -44, so it rests "above" the pickerview.
    // Borrowed from @Spark, thanks!
    UIToolbar *pickerDateToolbar = [[UIToolbar alloc] initWithFrame:CGRectMake(0, -44, 320, 44)];
    pickerDateToolbar.barStyle = UIBarStyleBlackTranslucent;
    [pickerDateToolbar sizeToFit];

    NSMutableArray *barItems = [[NSMutableArray alloc] init];

    UIBarButtonItem *flexSpace = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:self action:nil];
    [barItems addObject:flexSpace];

    // The action can whatever you want, but it should dimiss the picker.
    UIBarButtonItem *doneBtn = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone target:self action:@selector(backgroundTapped:)];
    [barItems addObject:doneBtn];

    [pickerDateToolbar setItems:barItems animated:YES];
    [_picker addSubview:pickerDateToolbar];

    // If you have a UITabBarController, you should add the picker as a subview of it
    // so it appears to go over the tabbar, not under it. Otherwise you can add it to 
    // self.view
    [self.tabBarController.view addSubview:_picker];

    // Animate it moving up
    [UIView animateWithDuration:.3 animations:^{
        [_picker setCenter:CGPointMake(160, [[UIScreen mainScreen] bounds].size.height - 148)]; //148 seems to put it in place just right.
    } completion:^(BOOL finished) {
        // When done, place an invisible button on the view behind the picker, so if the
        // user "taps to dismiss" the picker, it will go away. Good user experience!
        self.backgroundTapButton = [UIButton buttonWithType:UIButtonTypeCustom];
        _backgroundTapButton.frame = CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height);
        [_backgroundTapButton addTarget:self action:@selector(backgroundTapped:) forControlEvents:UIControlEventTouchUpInside];
        [self.view addSubview:_backgroundTapButton];
    }];

}

// And lastly, the method to hide the picker.  You should handle the picker changing
// in a method with UIControlEventValueChanged on the pickerview.
- (void)backgroundTapped:(id)sender {

    [UIView animateWithDuration:.3 animations:^{
        _picker.center = CGPointMake(160, [[UIScreen mainScreen] bounds].size.height + _picker.frame.size.height);
    } completion:^(BOOL finished) {
        [_picker removeFromSuperview];
        self.picker = nil;
        [self.backgroundTapButton removeFromSuperview];
        self.backgroundTapButton = nil;
    }];
}

答案 7 :(得分:7)

要添加到marcio的强大解决方案,dismissActionSheet:可以实现如下。

  1. 将一个ActionSheet对象添加到.h文件中,合成它并在.m文件中引用它。
  2. 将此方法添加到您的代码中。

    - (void)dismissActionSheet:(id)sender{
      [_actionSheet dismissWithClickedButtonIndex:0 animated:YES];
      [_myButton setTitle:@"new title"]; //set to selected text if wanted
    }
    

答案 8 :(得分:3)

我认为这是最佳方式。

ActionSheetPicker-3.0

它几乎是每个人的建议,但使用块,这是一个很好的接触!

答案 9 :(得分:2)

自从iOS 8以来,它无法正常工作,因为Apple更改了UIActionSheet的内部实施。请参阅Apple Documentation

  

子类注释

     

UIActionSheet不是设计为子类,也不是   是否应该向其层次结构添加视图。如果您需要提供比UIActionSheet API提供的更多自定义的工作表,您可以创建自己的工作表并使用presentViewController以模态方式呈现它:animated:completion:。

答案 10 :(得分:1)

我喜欢Wayfarer采用的方法和flexaddicted,但发现(如aZtral)它不起作用,因为backgroundTapButton是唯一响应用户交互的元素。这导致我将所有三个子视图:_picker,_pickerToolbar和backgroundTapButton放在一个包含视图(弹出窗口)中,然后在屏幕上和屏幕上进行动画处理。我还需要_pickerToolbar上的“取消”按钮。以下是弹出视图的相关代码元素(您需要提供自己的选择器数据源和委托方法)。

#define DURATION            0.4
#define PICKERHEIGHT        162.0
#define TOOLBARHEIGHT       44.0

@interface ViewController ()
@property (nonatomic, strong) UIView        *popup;
@property (nonatomic, strong) UIPickerView  *picker;
@property (nonatomic, strong) UIToolbar     *pickerToolbar;
@property (nonatomic, strong) UIButton      *backgroundTapButton;
@end

-(void)viewDidLoad {
    // These are ivars for convenience
    rect = self.view.bounds;
    topNavHeight = self.navigationController.navigationBar.frame.size.height;
    bottomNavHeight = self.navigationController.toolbar.frame.size.height;
    navHeights = topNavHeight + bottomNavHeight;
}

-(void)showPickerView:(id)sender {
    [self createPicker];
    [self createToolbar];

    // create view container
    _popup = [[UIView alloc] initWithFrame:CGRectMake(0.0, topNavHeight, rect.size.width, rect.size.height - navHeights)];
    // Initially put the centre off the bottom of the screen
    _popup.center = CGPointMake(rect.size.width / 2.0, rect.size.height + _popup.frame.size.height / 2.0);
    [_popup addSubview:_picker];
    [_popup insertSubview:_pickerToolbar aboveSubview:_picker];

    // Animate it moving up
    // This seems to work though I am not sure why I need to take off the topNavHeight
    CGFloat vertCentre = (_popup.frame.size.height - topNavHeight) / 2.0;

    [UIView animateWithDuration:DURATION animations:^{
        // move it to a new point in the middle of the screen
        [_popup setCenter:CGPointMake(rect.size.width / 2.0, vertCentre)];
    } completion:^(BOOL finished) {
        // When done, place an invisible 'button' on the view behind the picker,
        // so if the user "taps to dismiss" the picker, it will go away
        self.backgroundTapButton = [UIButton buttonWithType:UIButtonTypeCustom];
        _backgroundTapButton.frame = CGRectMake(0, 0, _popup.frame.size.width, _popup.frame.size.height);
        [_backgroundTapButton addTarget:self action:@selector(doneAction:) forControlEvents:UIControlEventTouchUpInside];
        [_popup insertSubview:_backgroundTapButton belowSubview:_picker];
        [self.view addSubview:_popup];
    }];
}

-(void)createPicker {
    // To use the default UIPickerView frame of 216px set frame to CGRectZero, but we want the 162px height one
    CGFloat     pickerStartY = rect.size.height - navHeights - PICKERHEIGHT;
    self.picker = [[UIPickerView alloc] initWithFrame:CGRectMake(0.0, pickerStartY, rect.size.width, PICKERHEIGHT)];
    _picker.dataSource = self;
    _picker.delegate = self;
    _picker.showsSelectionIndicator = YES;
    // Otherwise you can see the view underneath the picker
    _picker.backgroundColor = [UIColor whiteColor];
    _picker.alpha = 1.0f;
}

-(void)createToolbar {
    CGFloat     toolbarStartY = rect.size.height - navHeights - PICKERHEIGHT - TOOLBARHEIGHT;
    _pickerToolbar = [[UIToolbar alloc] initWithFrame:CGRectMake(0, toolbarStartY, rect.size.width, TOOLBARHEIGHT)];
    [_pickerToolbar sizeToFit];

    NSMutableArray *barItems = [[NSMutableArray alloc] init];
    UIBarButtonItem *cancelButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemCancel target:self action:@selector(cancelAction:)];
    [barItems addObject:cancelButton];

    // Flexible space to make the done button go on the right
    UIBarButtonItem *flexSpace = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:self action:nil];
    [barItems addObject:flexSpace];

    // The done button
    UIBarButtonItem *doneButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone target:self action:@selector(doneAction:)];
    [barItems addObject:doneButton];
    [_pickerToolbar setItems:barItems animated:YES];
}

// The method to process the picker, if we have hit done button
- (void)doneAction:(id)sender {
    [UIView animateWithDuration:DURATION animations:^{
        _popup.center = CGPointMake(rect.size.width / 2.0, rect.size.height + _popup.frame.size.height / 2.0);
    } completion:^(BOOL finished) { [self destroyPopup]; }];
    // Do something to process the returned value from your picker
}

// The method to process the picker, if we have hit cancel button
- (void)cancelAction:(id)sender {
    [UIView animateWithDuration:DURATION animations:^{
        _popup.center = CGPointMake(rect.size.width / 2.0, rect.size.height + _popup.frame.size.height / 2.0);
    } completion:^(BOOL finished) { [self destroyPopup]; }];
}

-(void)destroyPopup {
    [_picker removeFromSuperview];
    self.picker = nil;
    [_pickerToolbar removeFromSuperview];
    self.pickerToolbar = nil;
    [self.backgroundTapButton removeFromSuperview];
    self.backgroundTapButton = nil;
    [_popup removeFromSuperview];
    self.popup = nil;
}