Подтвердить что ты не робот

Отображение сделанной кнопки в UIPickerview

Я написал следующий код в методе viewDidLoad:

categoryPickerView=[[UIPickerView alloc]init];
categoryPickerView.alpha = 0;
[self.view addSubview:categoryPickerView];
categoryPickerView.delegate=self;
categoryPickerView.tag=1;

и вызвал этот метод, чтобы скрыть представление сборщика

- (IBAction)hidePickerView:(id)sender {
    [UIView beginAnimations:nil context:nil];
    [UIView setAnimationDuration:0.6];
    CGAffineTransform transfrom = CGAffineTransformMakeTranslation(0, 200);
    categoryPickerView.transform = transfrom;
    categoryPickerView.alpha = categoryPickerView.alpha * (-1) + 1;
    [UIView commitAnimations];
}

Моя проблема заключается в том, что я хочу отобразить кнопку "Готово" на представлении выбора, а вид выбора должен скрываться при нажатии кнопки.

4b9b3361

Ответ 1

Вы можете использовать этот код,

UIToolbar *toolBar= [[UIToolbar alloc] initWithFrame:CGRectMake(0,0,320,44)];
[toolBar setBarStyle:UIBarStyleBlackOpaque];
UIBarButtonItem *barButtonDone = [[UIBarButtonItem alloc] initWithTitle:@"Done" 
    style:UIBarButtonItemStyleBordered target:self action:@selector(changeDateFromLabel:)];
toolBar.items = @[barButtonDone];
barButtonDone.tintColor=[UIColor blackColor];
[pickerView addSubview:toolBar];
//(or)pickerView.inputAccessoryView = toolBar;

и установите метод действия кнопки для changeDateFromLabel:

-(void)changeDateFromLabel:(id)sender
{
   [[your UI Element] resignFirstResponder];
}

Ответ 2

Вы можете создать панель просмотра и добавить панель инструментов с кнопкой "Готово" и UIPickerView в качестве подзаголовков

- (void)createInputView {
    CGFloat screenWidth = [UIScreen mainScreen].bounds.size.width;

    UIToolbar *toolBar= [[UIToolbar alloc] initWithFrame:CGRectMake(0, 0, screenWidth, 44)];
    [toolBar setBarStyle:UIBarStyleDefault];
    UIBarButtonItem *flex = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:self action:nil];

    UIBarButtonItem *barButtonDone = [[UIBarButtonItem alloc] initWithTitle:@"Done"
                                                                  style:UIBarButtonItemStyleBordered
                                                                 target:self
                                                                 action:@selector(doneClicked)];
    toolBar.items = @[flex, barButtonDone];
    barButtonDone.tintColor = [UIColor blackColor];

    UIPickerView *picker = [[UIPickerView alloc] initWithFrame:CGRectMake(0, toolBar.frame.size.height, screenWidth, 200)];
    picker.delegate = self;
    picker.dataSource = self;
    picker.showsSelectionIndicator = YES;


    UIView *inputView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, screenWidth, toolBar.frame.size.height + picker.frame.size.height)];
    inputView.backgroundColor = [UIColor clearColor];
    [inputView addSubview:picker];
    [inputView addSubview:toolBar];

    textField.inputView = inputView;
}

- (void)doneClicked {
    [textField resignFirstResponder];
}

Ответ 3

Вам необходимо использовать UIToolbar в качестве дополнительного вида: Попробуйте следующее:

#pragma mark - PickerView for Location Selection

- (UIPickerView *)locationsPicker {
    if ( locationsPicker == nil ) {
        locationsPicker = [[UIPickerView alloc] init];
        locationsPicker.delegate = self;
        locationsPicker.dataSource = self;
        locationsPicker.showsSelectionIndicator = YES;
    }
    return locationsPicker;
}

- (UIToolbar *)accessoryView {
    if ( accessoryView == nil ) {
        accessoryView = [[UIToolbar alloc] initWithFrame:CGRectMake(0, 0, 320, 44)];

        UIBarButtonItem *doneButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:
                                       UIBarButtonSystemItemDone
                                       target:self
                                       action:@selector(onLocationSelection)];
        [accessoryView setItems:[NSArray arrayWithObject:doneButton]];
    }
    return accessoryView;
}

- (void)onLocationSelection {
    NSInteger row = [self.locationsPicker selectedRowInComponent:0];
    if ( [Location isFirstResponder] ) {
       NSLog(@"%@", [listOfLocations objectAtIndex:row]);
        [Location resignFirstResponder];
    }
}

Ответ 4

UIToolbar с кнопкой "Готово" следует добавить в inputAccessoryView представления, что становится первым ответчиком. Поскольку класс UIView наследует от UIResponder, любое представление потенциально может содержать inputView и inputAccessoryView. Таким образом, вместо того, чтобы программно выполнять анимацию вручную, вы можете использовать поведение анимации по умолчанию, которое появляется с отображением/скрытием анимации клавиатуры UIResponder.

  • Подкласс a UIView и переопределить свойства inputView и inputAccessoryView и сделать их readwrite. В этом примере я буду подклассифицировать UITableViewCell.

    // FirstResponderTableViewCell.h
    @interface FirstResponderTableViewCell : UITableViewCell
    @property (readwrite, strong, nonatomic) UIView *inputView;
    @property (readwrite, strong, nonatomic) UIView *inputAccessoryView;
    @end
    
  • Переопределить canBecomeFirstResponder в реализации вашего подкласса.

    // FirstResponderTableViewCell.m
    - (BOOL)canBecomeFirstResponder {
        return YES;
    }
    
  • В вашем представлении контроллер, создайте и назначьте панель инструментов выбора и входной аксессуар

    // MyViewController.m
    - (void)viewDidLoad {
        [super viewDidLoad];
        UIPickerView *pickerView = [[UIPickerView alloc] init];
        UIToolbar *accessoryToolbar = [UIToolbar alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 44)];
        // Configure toolbar .....
    
        // note: myFirstResponderTableViewCell is an IBOutlet to a static cell in storyboard of type FirstResponderTableViewCell
        self.myFirstResponderTableViewCell.inputView = pickerView;
        self.myFirstResponderTableViewCell.inputAccessoryView = accessoryToolbar;
    }
    
  • Не забудьте назначить первый ответчик на просмотр, когда это необходимо (например, внутри - tableView:didSelectRowAtIndexPath:)

    [self.myFirstResponderTableViewCell becomeFirstResponder];
    

Надеюсь, что это поможет.

Ссылка: http://blog.swierczynski.net/2010/12/how-to-create-uipickerview-with-toolbar-above-it-in-ios/

Ответ 5

Попробуйте это.

UIPickerView *cityPicker = [[UIPickerView alloc] initWithFrame:CGRectZero];
cityPicker.delegate = self;
cityPicker.dataSource = self;
[cityPicker setShowsSelectionIndicator:YES];
txtText.inputView = cityPicker;
// Create done button in UIPickerView
UIToolbar*  mypickerToolbar = [[UIToolbar alloc] initWithFrame:CGRectMake(0, 0, 320, 56)];
mypickerToolbar.barStyle = UIBarStyleBlackOpaque;
[mypickerToolbar 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(pickerDoneClicked)];
[barItems addObject:doneBtn];
[mypickerToolbar setItems:barItems animated:YES];
txtText.inputAccessoryView = mypickerToolbar;  // set the toolbar as input accessory view  for uitextfield, not the pickerview.

http://technopote.com/how-to-make-multiple-uipickerview-in-a-single-view/

Ответ 6

Решение для копирования-папок!

Это работает в iOS 10 (и, возможно, в других версиях), я написал этот код 9/4/2017.

Мне нужно было объединить другие ответы, чтобы получить то, что я хотел, это кнопка Cancel, кнопка Done и представление выбора, которое отображало бы/скрывало бы нажатие кнопки. Игнорируйте тот факт, что на моем снимке экрана есть только один элемент в сборщике. У меня есть только один элемент в моем массиве. Я тестировал несколько элементов, он отлично работает.

введите описание изображения здесь

Отказ от ответственности! Я тестировал и использовал этот код. Я обобщил имена в моем примере, поэтому заранее прошу прощения, если я пропустил один, и имена свойств не совпадают.

Чтобы иметь pickerView, который появляется нажатием кнопки, вам нужно создать dummyTextField (типа UITextField в любом месте вашего контроллера просмотра). Это связано с тем, что UIPickerView разработанный для работы с UITextFields. Чтобы имитировать показ и скрытие сборщика, ваши кнопки должны вызвать методы dummyTextField becomeFirstResponder и resignFirstResponder (примеры ниже)

Шаг первый

Создайте собственный класс источника данных. MyObj - это класс, в котором вы хотите, чтобы элементы отображались в подборщике.

В .h:

#import <UIKit/UIKit.h>
@class myObj;

@interface PickerDataSource : NSObject <UIPickerViewDataSource, UIPickerViewDelegate>
@property (nonatomic, strong) MyObj *selectedObject;
@end

В .m:

#import "PickerDataSource.h"
#import "MyObj.h"

@implementation PickerDataSource

- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component {
    self.selectedObject = mySourceArray[row];
}

- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component {
    return mySourceArray.count;
}

- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView {
    return 1;
}

- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component {
    return ((MyObj *)mySourceArray[row]).myTitle;
}

- (CGFloat)pickerView:(UIPickerView *)pickerView widthForComponent:(NSInteger)component {
    int sectionWidth = 300;
    return sectionWidth;
}

@end

Шаг второй. В вашем контроллере просмотра импортируйте пользовательский источник данных, делегируйте и задайте свойства: (Вы должны включить делегат текстового поля!)

#import "PickerDataSource.h"

@interface MyViewController () <UIPickerViewDelegate, UITextFieldDelegate>
@property (strong, nonatomic) PickerDataSource *pickerDataSource;
@property (strong, nonatomic) UIPickerView *picker;
@property (strong, nonatomic) UITextField *dummyTextField;
@end

Шаг третий

В вашем viewDidLoad вызовите [self setupPicker]; (вы создадите следующий метод)

Шаг четыре

Создать setupPicker

- (void)setupPicker {
    // init custom picker data source
    self.pickerDataSource = [PickerDataSource new];
    // init custom picker
    self.picker = [UIPickerView new];
    // set the picker dataSource and delegate to be your custom data source
    self.picker.dataSource = self.pickerDataSource;
    self.picker.delegate = self.pickerDataSource;
    self.picker.showsSelectionIndicator = YES;

    // next step is to write this configure method getting called here
    [self configurePickerSubviews];

    // lastly, add the dummyTextField to your view.
    [self.view addSubview:self.dummyTextField];
}

Шаг пять

Создать configurePickerSubviews

- (void)configurePickerSubviews {
    // A UIPickerView must be added as an inputView to a UITextField in order to be displayed on button tap
    // So you need to create a dummyTextField to do so.
    self.dummyTextField = [UITextField new];

    // Create a toolbar to add a done button
    UIToolbar *toolBar= [[UIToolbar alloc] initWithFrame:CGRectMake(0,0,[UIScreen mainScreen].bounds.size.width,44)];
    [toolBar setBarStyle:UIBarStyleDefault];
    UIBarButtonItem *done = [[UIBarButtonItem alloc] initWithTitle:@"Done" style:UIBarButtonItemStylePlain target:self action:@selector(locationPressed)];

    // Create a flex space so that done button will be right aligned
    UIBarButtonItem *flex = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:self action:nil];
    UIBarButtonItem *cancel = [[UIBarButtonItem alloc] initWithTitle:@"Cancel" style:UIBarButtonItemStylePlain target:self action:@selector(dismissPicker)];
    toolBar.items = @[cancel, flex, done];
    done.tintColor = [UIColor blackColor];

    [self.picker addSubview:toolBar];

    // Create an input view to add picker + done button as subviews
    UIView *inputView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, self.picker.frame.size.height + 44)];
    [self.picker setFrame:CGRectMake(0, 0, inputView.frame.size.width, inputView.frame.size.height)];
    inputView.backgroundColor = [UIColor clearColor];
    [inputView addSubview:self.picker];
    [inputView addSubview:toolBar];

    // Set custom inputView as container for picker view
    self.dummyTextField.inputView = inputView;

    // Hiding the textfield will hide the picker
    [self.dummyTextField setHidden:YES];
}

Шаг шесть

Настройте PickerDataSource так, чтобы он извлекал данные, которые вы хотите отобразить из вашего исходного массива.

Шаг 7

Нажмите Run!

Ответ 7

 #import "ViewController.h"

 @interface ViewController ()<UIPickerViewDelegate>
 {
UIPickerView *myPickerView;
NSArray *namesArray ;

 }
 @end

 @implementation ViewController

 -(void)viewDidLoad
 {
 [super viewDidLoad];
    namesArray=[[NSArray alloc]initWithObjects:@"a",@"b", nil];
   [self popoverWithInformation];


  }

 -(void)popoverWithInformation
 {
UIToolbar *pickerToolbar = [[UIToolbar alloc] initWithFrame:CGRectMake(0, 0, 320, 44)];
pickerToolbar.barStyle = UIBarStyleBlackOpaque;
[pickerToolbar sizeToFit];
NSMutableArray *barItems = [[NSMutableArray alloc] init];


UIBarButtonItem *cancelBtn = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemCancel target:self action:@selector(pickerCancel:)];
[barItems addObject:cancelBtn];

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

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



[pickerToolbar setItems:barItems animated:YES];


myPickerView = [[UIPickerView alloc] init];
myPickerView.delegate = self;
myPickerView.showsSelectionIndicator = YES;
CGRect pickerRect = myPickerView.bounds;
myPickerView.bounds = pickerRect;
myPickerView.frame = CGRectMake(0, 44, 320, 216);

UIView* popoverView = [[UIView alloc] initWithFrame:CGRectMake(0, 44, 320, 300)];
popoverView.backgroundColor = [UIColor whiteColor];
[popoverView addSubview:myPickerView];

[popoverView addSubview:pickerToolbar];
[self.view addSubview:popoverView];
 }
 -(void)pickerView:(UIPickerView *)pickerView didSelectRow: (NSInteger)row inComponent:(NSInteger)component {


 }

 // tell the picker how many rows are available for a given component
 -(NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component {

  return namesArray.count;
 }

 // tell the picker how many components it will have
 -(NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView {
return 1;
 }

 // tell the picker the title for a given component
 -(NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component {




return namesArray[row];
 }

 // tell the picker the width of each row for a given component
 -(CGFloat)pickerView:(UIPickerView *)pickerView widthForComponent:(NSInteger)component {
int sectionWidth = 300;

return sectionWidth;
 }

 -(void)pickerDone:(id)sender
 {


 }
 -(void)pickerCancel:(id)sender
 {


 }