How to get a certain subview from UIView by tag

前端 未结 6 1098
野趣味
野趣味 2021-02-03 21:00

I\'m a noob in Objective-C and I have one question.

I have one UILabel object that I adding to one UIView with this code:

UILabel *label = [         


        
相关标签:
6条回答
  • 2021-02-03 21:33

    Example with UILabel:

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

    good luck!

    0 讨论(0)
  • 2021-02-03 21:38

    You can get your subviews with for loop iteration

    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
    
    0 讨论(0)
  • 2021-02-03 21:38

    Swift 3.0 and Swift 4.0

    if let subLabel:UILabel = primaryView.viewWithTag(123) as? UILabel {
        subLabel.text = "do things here :-D"
    }
    
    0 讨论(0)
  • 2021-02-03 21:46

    You can get the subview with the code which others have mentioned, just like

    UILabel *tagLabel = (UILabel*)[view viewWithTag:1];
    

    But an important point to remember,

    • Make sure the parent view doesn't have the same tag value as of the subview. Otherwise the viewWithTag: method will return the receiver view (on which you are calling viewWithTag:) instead of returning the actual subview you want.

    So keep the parent view and child views tags distinct whenever you need to use viewWithTag:.

    0 讨论(0)
  • 2021-02-03 21:53

    If you are on the same view

    UILabel *tagLabel =  (UILabel*)[view viewWithTag:1];
    

    Also, if you want a new instance of UILabel

    UILabel *newTagLabel = [tagLabel copy];
    //customize new label here...
    [view addSubView:newTagLabel];
    
    0 讨论(0)
  • 2021-02-03 21:57

    You could use the viewWithTag: method.

    0 讨论(0)
提交回复
热议问题