0

我是一名 iOS 开发新手,如果能以编程方式在 UITableView 中创建多个 UISlider 和 UILabel 控件,我将不胜感激,如图所示:

小样

如上面的样机图片所示,我只需要在更改相应的滑块(在同一行)时更新相关的标签文本。

使用下面的代码,我可以为表格视图中的每一行动态创建多个滑块控件,但是当滑块的值发生更改时,我无法显示相应的标签并更新此标签文本。

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *ControlRowIdentifier = @"ControlRowIdentifier";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ControlRowIdentifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc]
                initWithStyle:UITableViewCellStyleDefault
                reuseIdentifier:ControlRowIdentifier];


        CGRect frame = CGRectMake(0.0, 0.0, 100.0, 10.0);
        UISlider *slider = [[UISlider alloc] initWithFrame:frame];
        [slider addTarget:self action:@selector(sliderAction:) forControlEvents:UIControlEventValueChanged];
        [slider setBackgroundColor:[UIColor clearColor]];
        slider.minimumValue = 1;
        slider.maximumValue = 70;
        slider.continuous = YES;
        slider.value = 30;

        cell.accessoryView = slider;
    }
    NSUInteger row = [indexPath row];
    NSString *rowTitle = [list objectAtIndex:row];
    cell.textLabel.text = rowTitle;

    return cell;
}

//Does not work
- (IBAction)sliderAction:(id)sender {
    UISlider *sliderControl = (UISlider *)sender;
    int SliderValue = (int)roundf(sliderControl.value);
    UILabel *sliderLabel;
    sliderLabel.text = [NSString stringWithFormat:@"%d", SliderValue];
    [self.view addSubview:sliderLabel];
}
4

2 回答 2

0

您应该将滑块创建移出 if 指令:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *ControlRowIdentifier = @"ControlRowIdentifier";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ControlRowIdentifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault
               reuseIdentifier:ControlRowIdentifier];
    }
    CGRect frame = CGRectMake(0.0, 0.0, 100.0, 10.0);
    UISlider *slider = [[UISlider alloc] initWithFrame:frame];
    [slider addTarget:self action:@selector(sliderAction:) forControlEvents:UIControlEventValueChanged];
    [slider setBackgroundColor:[UIColor clearColor]];
    slider.minimumValue = 1;
    slider.maximumValue = 70;
    slider.continuous = YES;
    slider.value = 30;

    cell.accessoryView = slider;

    NSUInteger row = [indexPath row];
    NSString *rowTitle = [list objectAtIndex:row];
    cell.textLabel.text = rowTitle;

    return cell;
}
于 2013-01-05T22:15:25.593 回答
0

我在这里看到了几个问题。

  1. 您永远不会实例化任何标签来显示滑块值。您需要实例化它并将其放入表格单元格的视图层次结构中。
  2. 您将 设置UITableViewDataSource为滑块操作的目标。这使得很难知道哪个标签对应于哪个滑块。您应该自定义 UITableViewCell,或者通过子类化或将 UIView 子类添加到contentView. 滑块应以单元格或视图子类为目标,并且标签更新可能发生在那里。还有其他方法可以做到这一点。
  3. 在您的sliderAction:方法中,您永远不会初始化sliderLabel变量。您需要将其设置为UILabel与单元格对应的实例,如上。
于 2013-01-05T22:21:03.440 回答