Objective c 如何通过标记从UIView获取某个子视图

Objective c 如何通过标记从UIView获取某个子视图,objective-c,uiview,uilabel,Objective C,Uiview,Uilabel,我是Objective-C的noob,我有一个问题 我有一个UILabel对象,我用此代码添加到一个UIView中: UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0,10,self.view.frame.size.width-15-70, 30)]; label.tag = 1; label.font = [PublicObject fontTexts:17]; label.textAlignment = NSTextAl

我是Objective-C的noob,我有一个问题

我有一个
UILabel
对象,我用此代码添加到一个UIView中:

UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0,10,self.view.frame.size.width-15-70, 30)];
label.tag = 1;
label.font = [PublicObject fontTexts:17];
label.textAlignment = NSTextAlignmentRight;
label.textColor = [UIColor whiteColor];
[cell setBackgroundColor:[UIColor clearColor]];

 UIView *view = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 320, 50)];
 view.backgroundColor = [PublicObject colorWithHexString:@"cd4110"];
 label.text = [filterData objectAtIndex:indexPath.row];
 view addSubview:label];
现在,我想在视图中获取一个子视图,其中该子视图具有标记=1,并将其保存在另一个对象上,如下所示:

UILabel *tagLabel;
tagLabel = // I want get one subview in view where tag = 1 

请帮助我了解如何执行此操作。

您可以使用此方法。

带有
UILabel的示例:

UILabel *label = (UILabel *)[self.view viewWithTag:1];

祝你好运

您可以使用for循环迭代获取子视图

for (UIView *i in self.view.subviews){
      if([i isKindOfClass:[UILabel class]]){
            UILabel *newLbl = (UILabel *)i;
            if(newLbl.tag == 1){
                /// Write your code
            }
      }
}
Swift

let label:UILabel = self.view.viewWithTag(1) as! UILabel

如果您在同一视图上

UILabel *tagLabel =  (UILabel*)[view viewWithTag:1];
另外,如果需要UILabel的新实例

UILabel *newTagLabel = [tagLabel copy];
//customize new label here...
[view addSubView:newTagLabel];

您可以使用其他人提到的代码获得子视图,就像

UILabel *tagLabel = (UILabel*)[view viewWithTag:1];
但重要的一点是要记住

  • 确保父视图的标记值与子视图的标记值不同。否则,
    viewWithTag:
    方法将返回receiver视图(在该视图上调用
    viewWithTag:
    ),而不是返回所需的实际子视图

因此,每当需要使用带有标记的视图时,请保持父视图和子视图标记的区别:

Swift 3、Swift 4和Swift 5

如果让子标签:UILabel=primaryView.viewWithTag(123)为?UILabel{
subLabel.text=“在这里做事:-D”
}

首先,可以有多个子视图和一个标记。所以正确的问题是“如何通过标签从uiview中获取子视图”。我的朋友,我想通过标签获取UILabel!!!如果在我看来有很多标签,我不能用这个。。。请使用标签指导我设置所有视图的唯一标签值,并使用标签访问对象。最快的代码不是taht,而是:UILabel tagLabel=(UILabel)[view viewWithTag:1];[view viewWithTag:x]还按层次进行搜索,而不仅仅是直接子对象。如果您想避免搜索子视图的子视图,这可能是一个很好的答案,但这是一种利基用例。或者,如果您想不惜一切代价避免找到不属于UILabel的匹配标记,则也可能需要使用此手动方法。请使用[UIView viewWithTag:]确保您的父视图与您的父视图没有相同的标记!!!我快要失去理智了。非常感谢。你的评论救了我的命。