【问题标题】:IOS 6 and Auto Layout custom button height wrongIOS 6和Auto Layout自定义按钮高度错误
【发布时间】:2013-08-02 23:01:45
【问题描述】:

我创建了一个非常简单的自定义平面按钮:

@implementation HAFlatButton

+ (id)buttonWithColor:(UIColor *)aColor
{
    id button = [super buttonWithType:UIButtonTypeCustom];

    [button setFlatColor:aColor];

    CGRect frame = [button frame];
    frame.size.height = 200;
    [button setFrame:frame];

    return button;
}

+ (id)defaultButton
{
    return [HAFlatButton buttonWithColor:[HAColors buttonColor]];
}

- (void)setFlatColor:(UIColor *)flatColor
{
    _flatColor = flatColor;
    [self setNeedsDisplay];
}

- (void)drawRect:(CGRect)rect {
    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
    CGContextRef context = UIGraphicsGetCurrentContext();

    UIBezierPath *path = [UIBezierPath bezierPathWithRoundedRect:rect cornerRadius:4.0];
    CGContextSaveGState(context);
    [path addClip];

    [_flatColor setFill];
    CGContextFillRect(context, rect);

    CGColorSpaceRelease(colorSpace);
}

@end

当我使用 [HAFlatButton defaultButton] 向我的自动布局添加一个按钮时,它只比按钮文本略高,但是当我向我的布局添加一个 [UIButton buttonWithType:UIButtonTypeRoundedRect] 时,它在标签周围有适当的插图.

我做错了什么?

【问题讨论】:

  • 您是否在代码中创建自动布局约束?
  • 使用自动布局时,您不设置任何框架。所有的大小和定位都是通过约束来完成的。
  • 是的,我正在使用 Masonry 在代码中创建我的自动布局约束。我最终在约束中设置了高度。

标签: ios uibutton autolayout


【解决方案1】:

您需要执行以下一项或多项操作:

添加高度限制。

覆盖intrinsicSize 返回值。

调整垂直内容拥抱优先级。

【讨论】:

  • 所以我猜当我调用 [UIButton buttonWithType:UIButtonTypeRoundedRect] 时,UIButtonTypeRoundedRect 是在设置intrinsicSize?
  • 一种肯定知道的方法。询问按钮。记录结果。许多 UI 元素都有计算的内在大小,尤其是带有标签的元素。获取 Eric Sadun 关于自动布局的新书。很有启发性。
猜你喜欢
  • 2018-03-02
  • 1970-01-01
  • 1970-01-01
  • 2019-01-24
  • 2013-08-06
  • 1970-01-01
  • 2012-10-21
  • 2016-08-07
  • 2021-10-19
相关资源
最近更新 更多