【问题标题】:Updating A UIView in customView field of UIBarButtonItem在 UIBarButtonItem 的 customView 字段中更新 UIView
【发布时间】:2015-08-03 10:02:48
【问题描述】:

我在导航栏中记录了一场比赛的得分。 我正在尝试更新 UIBarButtonItem 的 customView 中的 UILabel。 在 UILabel 上调用 setText 后,它没有得到更新。 我试图改变它的颜色只是为了测试,这也不起作用。
我试图通过调用 setNeedsDisplay 来更新 UILabel 我试图通过调用 setNeedsDisplay 来更新 UIBarButtonItem 中的 customView。 这些都不是实际上更新了视图。 我进行了调试,当代码到达我 NSLog 所在的行时,它会在控制台上执行并打印正确的值。

我还尝试通过调用来更新 navController 的整个视图。 (当前代码在下面这样做)

更新/刷新 UIBarButtonItem 的 customView 字段的正确方法是什么

UIBarButtonItem* backUIButton =[view.navigationItem.rightBarButtonItems objectAtIndex:1];// I have 2 items in rightBarButtonList
    UIView* settingFrame =backUIButton.customView;


    for (UIView *i in settingFrame.subviews){
        if([i isKindOfClass:[UILabel class]]){
            UILabel *newLbl = (UILabel *)i;
            if(newLbl.tag == 1){
                /// Write your code
                NSString *inStr = [NSString stringWithFormat:@"%ld", [Utility getCoins] ];
                NSLog(@"data : %@",inStr);
                [newLbl setTextColor:[UIColor redColor]];
                [newLbl setText:inStr];

                [view.navigationController.view setNeedsDisplay];
            }
        }
    }

谢谢

【问题讨论】:

    标签: ios uiview uinavigationbar uinavigationcontroller


    【解决方案1】:

    我只保留标签的一个属性

    例如 我有财产

    @property (weak,nonatomic)UILabel * numlabel;
    

    我在这里创建自定义栏项

    UIView * customView = [[UIView alloc] initWithFrame:CGRectMake(0, 0,80,40)];
    UILabel * label = [[UILabel alloc] init];
    label.text = @"1";
    label.frame = CGRectMake(0,0,80,40);
    self.numlabel = label;
    [customView addSubview:label];
    
    UIBarButtonItem * item = [[UIBarButtonItem alloc] initWithCustomView:customView];
    self.navigationItem.leftBarButtonItem = item;
    

    那么当我需要改变时

    self.numlabel.text = @"2";
    

    我用我的 XCode 进行了测试,效果很好

    【讨论】:

      【解决方案2】:
          @interface HomeViewController ()
          {
              UILabel *label;//Globally declare the label to make changes
          }
          - (void)viewDidLoad
          {
              [super viewDidLoad];
              label = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, 100, 30)];
              label.text = @"First";
              UIBarButtonItem *barButton = [[UIBarButtonItem alloc]initWithCustomView:label];//set label as barButtonItem
              self.navigationItem.rightBarButtonItem = barButton;
          }
      

      在这里,我用 buttonAction 更新了标签

          - (IBAction)buttonAction:(id)sender
          {
              label.text = @"second";//successfully updated the label
          }
      

      【讨论】:

      • 你能解释一下你的答案吗?
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-09-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-06-10
      相关资源
      最近更新 更多