gpt4 book ai didi

iphone - 如何从 UIAlertController 将行添加到 UIPickerView

转载 作者:行者123 更新时间:2023-12-03 21:14:47 25 4
gpt4 key购买 nike

我有一个 UIPickerView,它从

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

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

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

谢谢!

最佳答案

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

你声明了一个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;

}

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

希望有帮助。

关于iphone - 如何从 UIAlertController 将行添加到 UIPickerView,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30813017/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com