【问题标题】:Can I get the element by Tag from iOS?我可以从 iOS 中通过 Tag 获取元素吗?
【发布时间】:2011-04-09 02:47:25
【问题描述】:

我想取回一个按钮,我已经给那里分配了标签,我该怎么做?

【问题讨论】:

    标签: ios objective-c uiview uibutton


    【解决方案1】:
    //Get View using tag
            UITextField *textFieldInView = (UITextField*)[self.view viewWithTag:sender.tag+1000];
            UILabel *labelInView = (UILabel*)[self.view viewWithTag:sender.tag+2000];
    
    //Print its content based on the tags
            NSLog(@"The tag is %d ", textFieldInView.tag);
            NSLog(@"The tag is %d ", labelInView.tag);
            NSLog(@"The Content is %@ ", textFieldInView.text);
            NSLog(@"The Content is  %@ ", labelInView.text);
    

    【讨论】:

      【解决方案2】:

      使用viewWithTag 方法。例如如果您的按钮在控制器的视图中并且您的按钮标签为 100,则以下行将返回该按钮:

      UIButton *button = (UIButton *)[self.view viewWithTag:100];
      

      编辑:

      在 Swift 中使用特定标签获取视图 -

      let view = self.view.viewWithTag(100)
      

      如果你想确保你有特定类型的视图,比如 UIButton,你应该检查类型:

      if let button = self.view.viewWithTag(100) as? UIButton {
          //Your code
      }
      

      【讨论】:

        【解决方案3】:
        UIButton *button=(UIButton *)[self.view viewWithTag:tag]; 
        

        //现在你可以根据标签值获取你的按钮了

        【讨论】:

          猜你喜欢
          • 2012-02-29
          • 2013-02-06
          • 1970-01-01
          • 2019-08-03
          • 2011-07-11
          • 1970-01-01
          • 2014-01-09
          • 1970-01-01
          • 2014-04-04
          相关资源
          最近更新 更多