我是一名 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];
}