【问题标题】:How do I add rows to UIPickerView from UIAlertController如何从 UIAlertController 向 UIPickerView 添加行
【发布时间】:2015-06-12 22:24:12
【问题描述】:

我有一个UIPickerView,它从

中定义的数组中获取数据
friends = [NSArray arrayWithObjects: @"jim", @"joe", @"anne", nil];

我在选择器下方有一个按钮,用于向选择器添加新朋友。 当按下按钮时,会弹出一个UIAlertController,用户可以输入新朋友的名字。我可以将文本保存为字符串,但无法将其添加到数组中。我也尝试过使用NSMutableArray's。

我是新手,所以所有输入都会很棒。我已经查看了类似的问题以寻求帮助,但没有任何效果。

谢谢!

【问题讨论】:

    标签: iphone uipickerview uialertcontroller


    【解决方案1】:

    好的,我会试着解释一下:

    你声明了一个NSMutbleArray,你不能指望使用NSArray,因为它是不可变的,你需要修改内容。

        NSMutableArray *array;
        UIAlertController * view;
        @implementation ViewController
    
    
        - (void)viewDidLoad {
            [super viewDidLoad];
            NSArray* friends = [NSArray arrayWithObjects: @"jim", @"joe", @"anne", nil];
            array = [NSMutableArray arrayWithArray:friends];
    // I added a UIPickerView in the StoryBoard, connected it to a property and the delegates and datasources.
            self.pickerView.delegate = self;
        }
    

    然后你声明UIPickerView的dataSource:

    - (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView{
    
        return 1;
    
    }
    
    // returns the # of rows in each component..
    - (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component{
    
        return array.count;
    
    }
    - (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component{
    
        return array[row];
    
    }
    

    那么,然后你展示你的 UIAlertController,在这种情况下,我将在 TextViewReturn 中将其关闭。

    //This is an action connected to the button which will present the ActionController
    - (IBAction)addFriend:(id)sender {
    
    
    
        view =   [UIAlertController alertControllerWithTitle:@"Add Friend" message:@"Write the friend to add"preferredStyle:UIAlertControllerStyleAlert];
    
        [view addTextFieldWithConfigurationHandler:^(UITextField *textField) {
            textField.placeholder = @"Friend";
            textField.delegate = self;
            textField.tag = 01;
        }];
    
        [self presentViewController:view animated:YES completion:nil];
    
    }
    - (BOOL)textFieldShouldReturn:(UITextField *)textField{
    
        if(textField.tag == 01){
    
            [array insertObject:textField.text  atIndex:array.count];
            [view dismissViewControllerAnimated:YES completion:^{
                [self.pickerView reloadAllComponents];
            }];
    
            return YES;
    
        }
    
        return YES;
    
    }
    

    这或多或少是你能做的,我是最具体的,因为你说你是一个初学者。

    希望对你有帮助。

    【讨论】:

    • 感谢您的详细解答!这正是我想要的。在我试图用UIAlertAction 拯救新朋友之前。你的方法要容易得多。再次感谢。
    猜你喜欢
    • 1970-01-01
    • 2021-04-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-06
    相关资源
    最近更新 更多