所以,我有滑块添加UITextFields,但是当选择小于之前的Slider Value时,它不会更新/减去UITextField。是[self.view addSubview:textField];需要在for循环之外吗?提前谢谢。
- (IBAction) sliderValueChanged:(UISlider *)sender {
float senderValue = [sender value];
int roundedValue = senderValue * 1;
ingredientLabel.text = [NSString stringWithFormat:@"%d", roundedValue];
int moveYBy = 35;
int baseY = 140;
for(int y = 0; y < roundedValue; y++){
UITextField *textField = [[UITextField alloc] initWithFrame:CGRectMake(20, baseY, 227, 31)];
textField.text = [NSString stringWithFormat:@"%d", roundedValue];
textField.borderStyle = UITextBorderStyleRoundedRect;
baseY = baseY + moveYBy;
[self.view addSubview:textField];
[textField release];
NSLog(@"Adding %d fields!", roundedValue);
}
NSLog(@"%d", roundedValue);
}
答案 0 :(得分:2)
每次滑块值更改时,您都会创建N个文本字段(其中n是舍入值)。
相反,您应该将NSMutableArray设为iVar并存储所有文本字段,当roundedValue大于该数组中的文本字段数时,我们会添加更多。如果它更小,我们删除一些。
(我正在使用一个名为textFieldsArray的iVar,我也改变了为数组计算y的方式)
- (IBAction) sliderValueChanged:(UISlider *)sender {
float senderValue = [sender value];
int roundedValue = senderValue * 1;
ingredientLabel.text = [NSString stringWithFormat:@"%d", roundedValue];
for(int y = 0; y < roundedValue; y++){
if(y > [textFieldsArray count]){
UITextField *textField = [[UITextField alloc] initWithFrame:CGRectMake(20, 140 + 35 * y, 227, 31)];
textField.text = [NSString stringWithFormat:@"%d", roundedValue];
textField.borderStyle = UITextBorderStyleRoundedRect;
[self.view addSubview:textField];
[textFieldsArray addObject:textField];
[textField release];
NSLog(@"Adding %d fields!", roundedValue);
}
}
while([textFieldsArray count] > roundedValue){
UITextField *textField = [textFieldsArray lastObject];
[textField removeFromSuperview];
[textFieldsArray removeLastObject];
}
NSLog(@"%d", roundedValue);
}