【问题标题】:Override layoutSubviews to call [super layoutSubviews] and then find and reposition the button's view覆盖 layoutSubviews 调用 [super layoutSubviews] 然后找到并重新定位按钮的视图
【发布时间】:2011-11-10 11:16:41
【问题描述】:

我正在尝试重新定位我的UIBarButtonItem,使其边缘紧贴 UINavigationBar 的顶部和右侧。我找到了this accepted answer 如何做到这一点,但我真的不明白如何编码。

我首先创建了一个名为CustomNavBar 的新类,它继承自UINavigationBar。然后我把这个方法放到了实现中:

- (void) layoutSubviews
{


}

我不明白的是答案中的部分

call [super layoutSubviews] and then find and reposition the button's view.

如何编码?即使朝正确的方向轻推也会有所帮助。谢谢!

【问题讨论】:

    标签: iphone objective-c xcode cocoa-touch uinavigationbar


    【解决方案1】:

    在您调用layoutSubviews 之后找到您想要移动的按钮,因为每次调用layoutSubviews 时它都会重新定位到iOS 想要的位置。

    - (void) layoutSubviews
    {
        [super layoutSubviews];
    
        for (UIView *view in self.subviews) {   // Go through all subviews
            if (view == buttonYouWant) {  // Find the button you want
                view.frame = CGRectOffset(view.frame, 0, -5);   // Move it
            }
        }
    }
    

    【讨论】:

      【解决方案2】:

      您可以使用NSClassFromString 循环遍历子视图并比较当前视图是否是您想要的,例如:

      -(void)layoutSubviews {
          [super layoutSubviews];
          for (UIView *view in self.subviews) {
              if ([view isKindOfClass:NSClassFromString(@"TheClassNameYouWant")]) {
                  // Do whatever you want with view here
              }
          }
      }
      

      您也可以在 for 循环中使用 NSLog 来查看不同的子视图。

      【讨论】:

      • 您为什么要使用NSClassFromString 而不是[TheClassNameYouWant class]?在后一种情况下,您会在重构后收到警告,而在第一种情况下不会。
      • 我认为[TheClassNameYouWant class] 也应该更高效
      猜你喜欢
      • 1970-01-01
      • 2015-11-10
      • 1970-01-01
      • 2012-11-17
      • 1970-01-01
      • 2015-09-29
      • 1970-01-01
      • 2015-04-22
      • 1970-01-01
      相关资源
      最近更新 更多