【问题标题】:Manual positioning of titleLabel in a custom UIButton (using layoutSubviews)在自定义 UIButton 中手动定位 titleLabel(使用 layoutSubviews)
【发布时间】:2010-09-21 10:00:14
【问题描述】:

我为我的应用创建了一个 UIButton 子类,我需要手动将 titleLabel 重新定位为按钮高度的 1/4 左右。这个帖子; http://forums.macrumors.com/showthread.php?t=763140 似乎直接解决了同样的问题,解决方案简单易懂。但是,我未能实现这一点,因为从未调用过我对 layoutSubviews 的覆盖。我的按钮是静态的,所以 layoutSubviews 只需要第一次调用,但它永远不会。我的代码:

@interface MyButton : UIButton {}

@implementation MyButton

- (id)initWithFrame:(CGRect)frame
{
  self = [[UIButton buttonWithType:UIButtonTypeRoundedRect] retain];
  [[self layer] setCornerRadius:14.0f];
  [[self layer] setBorderWidth:3.0f];
  [[self layer] setMasksToBounds:YES];
  [self setBackgroundColor:[UIColor redColor]];
  [self setFrame:frame];
  return self;
}

- (void)layoutSubviews
{
  NSLog(@"layout subs\n");
  [super layoutSubviews];
}

@end

移动标签没有问题,但永远不会调用 layoutSubviews。我也尝试添加 layoutIfNeeded,但没有任何区别。更奇怪的是,我试图直接从构造函数调用 [self layoutSubviews] 但 layoutSubviews 仍然没有被调用!。我开始认为这甚至可能是 SDK 3.1.3 中的一个错误

谁能帮忙?!

【问题讨论】:

    标签: iphone uibutton overriding subclass layoutsubviews


    【解决方案1】:

    layoutSubviews 中,您可以对子视图进行布局更改。确保在方法内部:

    致电[super layoutSubviews]

    x 请勿在此处更改 self.frame 的值或 rect。如果这样做,它将递归调用layoutSubviews

    确保您只更改frame子视图

    From UIView Class Reference

    【讨论】:

      【解决方案2】:

      回答我自己的问题,看来我的子类化不正确。采用以下方法会导致 layoutSubviews 被正确调用:

      + (id)buttonWithFrame:(CGRect)frame {
        return [[[self alloc] initWithFrame:frame] autorelease];
      }
      
      - (id)initWithFrame:(CGRect)frame {
        if (self = [super initWithFrame:frame]) 
        {
          ...
          [self setFrame:frame];
        }
        return self;
      }
      

      希望对他人有所帮助

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-01-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多