我创建了一个包含UIViews的TableView,它包含一些其他元素。这些UIView是动态创建的,因为数据是从服务器调用的。在每个UIView里面都有一个UILabel和一个UIButtton。单击按钮后,我希望使用某个值更新相应的标签。我能够修改UIButton和视图本身,但无法修改UILabel。以下是调用UIButton时调用的方法示例。现在它将改变相应UIView的背景颜色,但标签元素不能按预期工作。如何完成修改作为UIView的子元素的标签元素?
- (void) heartPlus:(id)sender {
UIButton *button = (UIButton*) sender;
NSInteger id_num = button.tag;
UIView * view = (UIView *)[self.view.superview viewWithTag:id_num];
UILabel * label = (UILabel *)[view viewWithTag:id_num];
label.backgroundColor = [UIColor blueColor];
}
创建UIView并添加相应的元素。
UIView * msgView = [[[UIView alloc] initWithFrame:CGRectMake(0,offSet,320,120)] init];
[msgView setTag:someID];
// Add button
UIButton * buttonUpdate = [UIButton buttonWithType:UIButtonTypeRoundedRect];
buttonUpdate.tag = someID;
[buttonUpdate addTarget:self action:@selector(heartPlus:) forControlEvents:UIControlEventTouchUpInside];
UILabel * labelHeart = [[[UILabel alloc] initWithFrame:CGRectMake(280,100,20,10)] init];
labelHeart.tag = someID;
// Add each element to the msgView
[msgView addSubview:buttonUpdate];
[msgView addSubview:labelHeart];
答案 0 :(得分:0)
仍有一些代码丢失,但据我所知,heartPlus
方法中存在错误,viewWithTag
无法返回正确的视图。因此,backgroundColor
的分配失败。解释如下:
您首先获得包含UIButton
和UILabel
的视图的父视图。我假设您的视图层次结构如下所示:
所以,如果我假设下面的行中没有错误并且它返回正确的UITableViewCell
(或者其他任何视图都是UILabel
和UIButton
的父视图):< / p>
UIView * view = (UIView *)[self.view.superview viewWithTag:id_num];
我们可以清楚地看到UILabel
和UIButton
具有相同标签的问题。因此,如果您向UITableViewCell询问带有标记的视图,它将会失败 - 返回nil。
此问题有多种解决方案,但问题仍然存在。
请勿为UILabel
提供与UIButton
相同的标记。
我假设你是Objective-C的初学者,所以我建议你先看看UIViews如何工作的一些教程。但为了让您更轻松,这里有几个选择:
UIView
属性创建UIView
的自定义子类。 UILabel
和UIButton
使用唯一标记。要在点击时找到正确的id_num
,请使用内省和sender
的{{1}},这是通过方法传递给您的。{/ li>
superview
的子视图属性(这是一个数组)并手动查找UILabel - 如果只有一个UIView
或者您正在查找所有这些,则可以正常工作但在任何一种情况下,您都需要重新考虑UILabel
的工作原理。向UITableView
询问self.view.superview
并不是一个好习惯,此时您的方法可能已失败。