开发者

uislider adding uitextfield but not updating

So, I have the slider adding UITextFields but it's not updating/subtracting UITextField's when selecting less than the previous Slider Value. Does [self.view addSubview:textField]; need to be outside of the for loop? Thanks in advance.

- (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]开发者_如何学Go;
    textField.borderStyle = UITextBorderStyleRoundedRect;
    baseY = baseY + moveYBy;
    [self.view addSubview:textField];
    [textField release];
    NSLog(@"Adding %d fields!", roundedValue);
}
NSLog(@"%d", roundedValue);
}


You are creating N text fields everytime the slider value changes (where n is the rounded value).

Instead, you should make an NSMutableArray an iVar and store all the text fields there, when roundedValue is bigger than the number of text fields in that array, we add more. When it's smaller, we remove some.

(I'm using an iVar called textFieldsArray, and I also changed a little the way the y is calculated for the arrays)

- (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);
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜