Показването на UIPickerView с UIActionSheet в iOS8 не работи

Показването на UIPickerView с UIActionSheet в iOS8 не работи

Кодът работи в iOS7, но не работи в iOS8. Сигурен съм, че е така, защото UIActionSheet е остарял в iOS8 и Apple препоръчва да се използва UIAlertController.

Но как да го направя в iOS8? Трябва ли да използвам UIAlertController?

iOS7:
въведете описание на изображението тук

iOS8:
въведете описание на изображението тук

РЕДАКТИРАНЕ:

Моят проект в GitHub решава проблема.


person Gabriel.Massana    schedule 20.06.2014    source източник
comment
Моят проект решава проблема: github.com/GabrielMassana/Picker-iOS8   -  person Gabriel.Massana    schedule 26.07.2014
comment
Можете да проверите моето решение тук: stackoverflow.com/questions/24366437/   -  person ki.bowox    schedule 29.09.2014
comment
@Gabriel.Massana, моля, прегледайте отговора ми stackoverflow.com/a/26731722/1698467 изглежда, това сте вие търся!   -  person skywinder    schedule 11.04.2015
comment
Добавянето на UIPickerView към UIAllertController ActionSheet все още работи по същия начин дори в iOS 9.3.1 без никакви логически промени. Кодът от моя пример е от един от моите проекти и е написан преди 2 години (в началото на Swift) и работи като чар. Вероятно имате някои аберации в кода, които причиняват неизправност на изгледа на лист с действия и неговите подизгледи. Вижте моя пример. Може да ви помогне в бъдещи проекти. stackoverflow.com/questions/25545982/   -  person Hristo Atanasov    schedule 16.05.2016


Отговори (8)


От справката за UIActionSheet:

UIActionSheet не е проектиран да бъде подклас, нито трябва да добавяте изгледи към неговата йерархия. Ако трябва да представите лист с повече персонализиране от предоставеното от UIActionSheet API, можете да създадете свой собствен и да го представите модално с presentViewController:animated:completion:.

Предполагам, че виждате точно защо.

Справката за UIAlertController няма подобен отказ от отговорност, но гледайки интерфейса, предполагам, че Apple ще го добави преди пускането.

Моята препоръка е просто да създадете малък изглед, съдържащ вашия инструмент за избор и бутони и да го показвате и скривате, ако е необходимо. Не е толкова трудно да се направи и не избутвате интерфейсите извън предназначението им.

person David Berry    schedule 20.06.2014
comment
Качих моя пример с UIView.animateWithDuration(duration: animations:, completion:). Работи перфектно. - person Gabriel.Massana; 23.06.2014
comment
Въпросът дали ще можем да подкласираме UIAlertController беше зададен stackoverflow.com/questions/24017657/, защото ще бъде интересен (и изненадващ) ход, ако Apple ни позволи да го подкласираме. Може би си струва да го следвате, защото ще предоставя актуализация, когато iOS8 бъде официално пуснат. - person Popeye; 23.06.2014

Пиша инструмента за избор на време от себе си вместо UIActionSheet в iOS8:

date = [NSDate date];

timePicker = [[UIDatePicker alloc] initWithFrame:CGRectMake(0, 44, 0, 0)];
timePicker.datePickerMode = UIDatePickerModeDateAndTime;
timePicker.hidden = NO;
timePicker.date = date;

displayFormatter = [[NSDateFormatter alloc] init];
[displayFormatter setTimeZone:[NSTimeZone localTimeZone]];
[displayFormatter setDateFormat:@"MM月dd日 EEE HH:mm"];

formatter = [[NSDateFormatter alloc] init];
[formatter setTimeZone:[NSTimeZone localTimeZone]];
[formatter setDateFormat:@"YYYY-MM-dd HH:mm:ss"];

startDisplayTimeString = [displayFormatter stringFromDate:timePicker.date];
startTimeString = [formatter stringFromDate:timePicker.date];

NSTimeInterval interval = 24*60*60*1;
NSDate *endDate = [[NSDate alloc] initWithTimeIntervalSinceNow:interval];
endDisplayTimeString = [displayFormatter stringFromDate:endDate];
endTimeString = [formatter stringFromDate:endDate];

[_startTimeLabel setText:startDisplayTimeString];
[_endTimeLabel setText:endDisplayTimeString];

[pickerViewPopup dismissWithClickedButtonIndex:1 animated:YES];

NSDateFormatter *dateFormatter =[[NSDateFormatter alloc] init];
[dateFormatter setTimeZone:[NSTimeZone localTimeZone]];
[dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];

UIToolbar *pickerToolbar = [[UIToolbar alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 64)];
pickerToolbar.tintColor = [UIColor whiteColor];
[pickerToolbar sizeToFit];

UIBarButtonItem *cancelBtn = [[UIBarButtonItem alloc] initWithTitle:@"Cancel" style:UIBarButtonItemStyleBordered target:self action:@selector(cancelBtnPressed:)];

[cancelBtn setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:
                                   [UIColor colorWithRed:253.0/255.0 green:68.0/255.0 blue:142.0/255.0 alpha:1.0],
                                   NSForegroundColorAttributeName,
                                   nil] forState:UIControlStateNormal];

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

UIBarButtonItem *titleButton;

float pickerMarginHeight = 168;


titleButton = [[UIBarButtonItem alloc] initWithTitle:@"title" style:UIBarButtonItemStylePlain target: nil action: nil];

[titleButton setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:
                                     [UIColor colorWithRed:253.0/255.0 green:68.0/255.0 blue:142.0/255.0 alpha:1.0],
                                     NSForegroundColorAttributeName,
                                     nil] forState:UIControlStateNormal];

UIBarButtonItem *doneBtn = [[UIBarButtonItem alloc] initWithTitle:@"OK" style:UIBarButtonItemStyleDone target:self action:@selector(setTimePicker)];

[doneBtn setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:
                                 [UIColor colorWithRed:253.0/255.0 green:68.0/255.0 blue:142.0/255.0 alpha:1.0],
                                 NSForegroundColorAttributeName,
                                 nil] forState:UIControlStateNormal];

NSArray *itemArray = [[NSArray alloc] initWithObjects:cancelBtn, flexSpace, titleButton, flexSpace, doneBtn, nil];

[pickerToolbar setItems:itemArray animated:YES];

if(iPad){

    [pickerToolbar setFrame:CGRectMake(0, 0, 320, 44)];

    UIViewController* popoverContent = [[UIViewController alloc] init];
    popoverContent.preferredContentSize = CGSizeMake(320, 216);
    UIView* popoverView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 216)];
    popoverView.backgroundColor = [UIColor whiteColor];
    [popoverView addSubview:timePicker];
    [popoverView addSubview:pickerToolbar];
    popoverContent.view = popoverView;
    popoverController = [[UIPopoverController alloc] initWithContentViewController:popoverContent];
    [popoverController presentPopoverFromRect:CGRectMake(0, pickerMarginHeight, 320, 216) inView:self.view permittedArrowDirections:UIPopoverArrowDirectionUp animated:YES];

}else{

    timeBackgroundView = [[UIView alloc] initWithFrame:CGRectMake(0, SCREEN_HEIGHT-300, 320, 246)];
    [timeBackgroundView setBackgroundColor:[UIColor colorWithRed:240/255.0 green:240/255.0 blue:240/255.0 alpha:1.0]];

    [timeBackgroundView addSubview:pickerToolbar];
    [timeBackgroundView addSubview:timePicker];

    [self.view addSubview:timeBackgroundView];}
person folse    schedule 12.09.2014

UIActionSheet е оттеглен в iOS8. Използвайте UIAlertController за iOS8 или по-нова версия

UIAlertController* alert = [UIAlertController alertControllerWithTitle:@"My Alert"
                            message:@"This is an action shhet."
                            preferredStyle:UIAlertControllerStyleActionSheet];

UIAlertAction* cameraAction = [UIAlertAction actionWithTitle:@"Take A Photo" style:UIAlertActionStyleDefault
                                    handler:^(UIAlertAction * action) {}];

UIAlertAction* galleryAction = [UIAlertAction actionWithTitle:@"From Gallery" style:UIAlertActionStyleDefault
                                                     handler:^(UIAlertAction * action) {}];

UIAlertAction * defaultAct = [UIAlertAction actionWithTitle:@"Cancel" style:UIAlertActionStyleCancel
                                                    handler:^(UIAlertAction * action) {}];

[alert addAction:cameraAction];
[alert addAction:galleryAction];
[alert addAction:defaultAct];

[self presentViewController:alert animated:YES completion:nil];

Реф.: UIAlertController

Пример: https://github.com/KiritVaghela/UIAlertController

person Kirit Vaghela    schedule 01.04.2015
comment
Това вероятно работи добре, но не използва UIPickerView, което е поисканото. - person ThomasW; 17.03.2016

Току-що го тествах с open.spotify url и получих същото
person Bulky_ooti    schedule 22.09.2014
comment
Благодаря Bulky_ooti. Вашето решение работи за мен, но с една лека модификация. Трябва първо да добавя pickerView като подизглед и след това да добавя pickerToolbar след това като подизглед. В противен случай лентата с инструменти за избор не е активна - person sogwiz; 29.10.2014

Сблъсквал съм се със същия проблем и го реших по този начин, че ще работи във всички версии на iOS

В iOS 8 Apple промени толкова много неща, че се сблъсках с един проблем в собствения си проект, така че просто искам да предложа решението в замяна на UIActionsheet.

в ios 8 UIActionsheet отхвърлен, както и неговите делегирани методи също са отхвърлени. Вместо това се използва UIAlertController с предпочитан стил
UIAlertControllerStyleActionSheet. можете да проверите и тази тема:

https://developer.apple.com/library/ios/documentation/Uikit/reference/UIActionSheet_Class/index.html

Този пример ще работи както в ios 8, така и в предишната му версия.

в .h файл декларирайте тази променлива

@interface demoProfileForBuyer{
 UIActionSheet *ac_sheet_fordate;
 UIToolbar *pickerToolBar_fordate;

 UIDatePicker *optionPickerDate;
 UIAlertController *alertController;
}

в .m файл

- (void)viewDidLoad
{

    [super viewDidLoad];
    pickerToolBar_fordate = [[UIToolbar alloc] initWithFrame:CGRectMake(-8, 0, 320, 44)];

    pickerToolBar_fordate.barStyle = UIBarStyleBlack;
    [pickerToolBar_fordate sizeToFit];

    NSMutableArray *barItemsDate = [[NSMutableArray allkioc] init];


    UIBarButtonItem *flexSpaceDate = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:self action:nil];
    [barItemsDate addObject:flexSpaceDate];

    UIBarButtonItem *doneBtnDate = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone target:self action:@selector(pickerViewDoneBirthday)];
    [barItemsDate addObject:doneBtnDate];

    [pickerToolBar_fordate setItems:barItemsDate animated:YES];

    optionPickerDate = [[UIDatePicker alloc] initWithFrame:CGRectMake(-8, 44, 320, 200)];


    optionPickerDate.datePickerMode = UIDatePickerModeDate;
    [optionPickerDate setMaximumDate: [NSDate date]];
    optionPickerDate.datePickerMode = UIDatePickerModeDate;
    optionPickerDate.hidden = NO;
    optionPickerDate.date = [NSDate date];
    optionPickerDate.backgroundColor = [UIColor whiteColor];

    if(IS_IOS_8){

        alertController = [UIAlertController alertControllerWithTitle:@"" message:@"" preferredStyle:UIAlertControllerStyleActionSheet];

        UIAlertAction *alertAction = [UIAlertAction actionWithTitle:@"" style:UIAlertActionStyleDefault handler:nil];
        [alertController addAction:alertAction];
        [alertController addAction:alertAction];
        [alertController addAction:alertAction];
        [alertController addAction:alertAction];        
        [alertController.view addSubview:pickerToolBar_fordate];
        [alertController.view addSubview:optionPickerDate];        
    } else {
    ac_sheet_fordate = [[UIActionSheet alloc] initWithTitle:@"test"
                                                   delegate:self
                                          cancelButtonTitle:@"cancel"
                                     destructiveButtonTitle:nil
                                          otherButtonTitles:@"dev",@"dev", nil];
    [ac_sheet_fordate setActionSheetStyle:UIActionSheetStyleBlackOpaque];
    [ac_sheet_fordate setBackgroundColor:[UIColor blackColor]];
    [ac_sheet_fordate addSubview:pickerToolBar_fordate];
    [ac_sheet_fordate addSubview:optionPickerDate];
    }
    }

// when date picker open 

   - (IBAction)showBirthdayPicker:(id)sender{
    //    self.view.frame = CGRectMake(0, -220, self.view.frame.size.width, self.view.frame.size.height);
    UIButton *btnsender = sender;
    //[ac_sheet_fordate showInView:self.view];
    self.scrForEditProfile.contentSize = CGSizeMake(320, 1000);
    if(IS_IOS_8){
            popover = alertController.popoverPresentationController;
            if (popover)
            {
                popover.sourceView = sender;
                popover.sourceRect = CGRectMake(0, btnsender.bounds.origin.y, btnsender.bounds.size.width, btnsender.bounds.size.height);

                popover.permittedArrowDirections = UIPopoverArrowDirectionAny;
            }
                [self presentViewController:alertController animated:YES completion:nil];

    } else {
    if(IS_IOS_7){
        [ac_sheet_fordate showInView:[UIApplication sharedApplication].keyWindow];
        ac_sheet_fordate.frame = CGRectMake(0, [UIScreen mainScreen].bounds.size.height-ac_sheet_fordate.frame.size.height, [UIScreen mainScreen].bounds.size.width, ac_sheet_fordate.frame.size.height);
    }
    else{
        [ac_sheet_fordate showInView:self.view];
    }
    }
    if(IS_IOS_7==FALSE && IS_HEIGHT_GTE_568==FALSE){
        [self.scrForEditProfile scrollRectToVisible:CGRectMake(self.txtDOB.frame.origin.x, self.txtDOB.frame.origin.y + 200, self.txtDOB.frame.size.width, self.txtDOB.frame.size.height) animated:NO];
    }
    else{
        [self.scrForEditProfile scrollRectToVisible:CGRectMake(self.txtDOB.frame.origin.x, self.txtDOB.frame.origin.y +300, self.txtDOB.frame.size.width, self.txtDOB.frame.size.height) animated:NO];
    }

}

// when date picker open user tap on done button

- (IBAction)pickerViewDoneBirthday{

    if(IS_IOS_8){
        [self.presentedViewController dismissViewControllerAnimated:NO completion:nil];

    } else {
        [ac_sheet_fordate dismissWithClickedButtonIndex:0 animated:YES];

    }

    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"dd/MM/yyyy"];
    birthday_date = optionPickerDate.date;
    [self.btnShowDatePicker setTitle:[formatter stringFromDate:optionPickerDate.date] forState:UIControlStateNormal];
    [self.btnShowDatePicker setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [self.btnShowDatePicker setTitleColor:[UIColor blackColor] forState:UIControlStateHighlighted];
    self.scrForEditProfile.contentSize=CGSizeMake(320 , 700);
    [self.scrForEditProfile scrollsToTop];

}

можете да проверите и моя блог, http://ioscodesample.blogspot.in/2014/10/ios-8-changes-for-actionsheet.html

Благодаря.

person Banker Mittal    schedule 13.10.2014

Имам същия проблем с вас, показването на UIPickerView с UIActionSheet не работи в iOS 8. Тъй като UIActionSheet е остарял и Apple препоръчва да се използва UIAlertController. Така че трябва да закръглим, за да навием.

Написах код за разрешаване на моя случай. Надявам се, че може да ви помогне.

#define CONTENT_HEIGHT 478

- (void)initSheetWithWidth:(CGFloat)aWidth
{
    if (SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(@"8.0")) {
        UIAlertController *sheet = [UIAlertController alertControllerWithTitle:@"hack space" message:@"\n\n\n\n\n\n\n\n\n\n\n" preferredStyle:UIAlertControllerStyleActionSheet];
        [sheet.view setBounds:CGRectMake(7, 0, aWidth, CONTENT_HEIGHT)]; // Kinda hacky
        self.sheet = sheet;
    } else {
        UIActionSheet *sheet = [[UIActionSheet alloc] init];
        self.sheet = sheet;
    }

    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, aWidth, CONTENT_HEIGHT)];
    [view setBackgroundColor:[UIColor whiteColor]];

    UIToolbar *toolbar = [[UIToolbar alloc]
                          initWithFrame:CGRectMake(0, 0, aWidth, 0)];
    toolbar.barStyle = UIBarStyleDefault;
    [toolbar sizeToFit];

    [toolbar setItems:@[
                        [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemCancel target:self action:@selector(pickerSheetCancel)],
                        [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil],
                        [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone target:self action:@selector(pickerSheetDone)]
                        ]];

    UIDatePicker *picker = [[UIDatePicker alloc]
                            initWithFrame:CGRectMake(0, toolbar.bounds.size.height, aWidth, 0)];


    if (SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(@"8.0")) {
        UIAlertController *sheet = self.sheet;
        [view addSubview:toolbar];
        [view addSubview:picker];
        [sheet.view addSubview:view];
    } else {
        UIActionSheet *sheet = self.sheet;
        [sheet addSubview:toolbar];
        [sheet addSubview:picker];
    }

    self.picker = picker;
}

- (void)showWithDate:(NSDate*)date {
    if (SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(@"8.0")) {
        // Reload and select first item
        [self.picker setDate:date];

        [self.parentViewController presentViewController:self.sheet animated:YES completion:nil];
    } else {
        UIActionSheet *sheet = self.sheet;
        [self.sheet showInView:self.containerView];

        // XXX: Kinda hacky, but seems to be the only way to make it display correctly.
        [self.sheet
         setBounds:CGRectMake(0, 0,
                              self.containerView.frame.size.width,
                              sheet.frame.size.height - CONTENT_HEIGHT)];

        // Reload and select first item
        [self.picker setDate:date];

        [UIView animateWithDuration:0.25 animations:^{
            [self.sheet
             setBounds:CGRectMake(0, 0,
                                  self.containerView.frame.size.width,
                                  sheet.frame.size.height)];
        }];
    }
}

Мисля, че всичко е, за да се реши този проблем. Приятно кодиране!

person Thanh Vũ Trần    schedule 19.03.2015
comment
какво е self.sheet и self.picker? - person Aruna kumari; 15.05.2015
comment
@Arunakumari, има id обект и UIPickerView. ..свойства (неатомни, силни) идентификационен лист; ..свойство (неатомно, силно) UIPickerView *picker; - person Thanh Vũ Trần; 15.05.2015
comment
Мисля, че не трябва да променяме изгледа на UIAlertViewController. Документацията на Apple казва, че е частна. Класът UIAlertController е предназначен да се използва такъв, какъвто е и не поддържа подкласове. Йерархията на изгледите за този клас е частна и не трябва да се променя. - person Naga Mallesh Maddali; 10.11.2015
comment
@NagaMalleshMaddali прав си, този начин не се препоръчва - person Thanh Vũ Trần; 23.11.2015

Swift 5

Можете да използвате UIAlertController, за да направите това.

@IBAction func btnActionDate(_ sender: Any) {
        let picker = UIPickerView(frame: CGRect(x: 0, y: 50, width: self.view.frame.size.width - 16.0, height: 150))
        picker.delegate = self
        picker.dataSource = self

//        let message = "\n\n\n\n\n\n"
        let alert = UIAlertController(title: "Title of Action Sheet", message: "", preferredStyle: UIAlertController.Style.actionSheet)
        alert.isModalInPopover = true

        picker.reloadAllComponents()

        //Add the picker to the alert controller
        alert.view.addSubview(picker)

        // For setting height of Action sheet
        let height:NSLayoutConstraint = NSLayoutConstraint(item: alert.view!, attribute: NSLayoutConstraint.Attribute.height, relatedBy: NSLayoutConstraint.Relation.equal, toItem: nil, attribute: NSLayoutConstraint.Attribute.notAnAttribute, multiplier: 1, constant: 350)
        alert.view.addConstraint(height)


        let okAction = UIAlertAction(title: "Done", style: .default, handler: {
            (alert: UIAlertAction!) -> Void in
            let fetchedObj = picker.selectedRow(inComponent: 0)
        })
        alert.addAction(okAction)
        let cancelAction = UIAlertAction(title: "Cancel", style: .cancel, handler: nil)
        alert.addAction(cancelAction)
        self.present(alert, animated: true, completion: nil)
    }

Задайте делегатите и източника на данни на pickerView по този начин

class MyViewController: UIViewController, UIPickerViewDelegate, UIPickerViewDataSource

задайте функциите за делегат и източник на данни

func numberOfComponents(in pickerView: UIPickerView) -> Int {
        return 1
    }

    func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {

            return arrayMonthData.count

    }

    func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {

            return arrayMonthData[row]

    }

    func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {

    }

    func pickerView(_ pickerView: UIPickerView, widthForComponent component: Int) -> CGFloat {
        return self.view.frame.size.width - 16.0
    }

    func pickerView(_ pickerView: UIPickerView, rowHeightForComponent component: Int) -> CGFloat {
        return 36.0
    }
person Amal T S    schedule 11.04.2019

Опитайте тази.

UIAlertController *alertController = [UIAlertController alertControllerWithTitle:nil
                                                               message:@"\n\n\n\n\n\n\n\n\n\n\n"
                                                               preferredStyle:UIAlertControllerStyleActionSheet];

__weak typeof(self) weakSelf = self;
UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
    [weakSelf pickActionSheetFinishAction];
}];

[alertController addAction:cancelAction];
[alertController.view addSubview:self.topicPickView];
[self presentViewController:alertController animated:YES completion:nil];
person fish.wang    schedule 24.10.2014