如何创建视图可以通过它的子视图调整大小?

时间:2014-01-05 10:05:25

标签: ios

我有一个观点:

@interface MyView : UIView

@property (nonatomic, retain, readonly) UILabel  *titleLabel;

@end

UILabel可以通过内容确定其框架。我想在标题标签的文本发生变化时使MyView自动调整大小。

我在MyView中实现了这个方法,它可以通过自动布局功能确定视图的大小:

- (CGSize)intrinsicContentSize
{
    CGSize size = [super intrinsicContentSize];
    CGSize labelSize = [_titleLabel intrinsicContentSize];
    size.height = labelSize.height;
    size.width = labelSize.width + 50;

    return size;
}

这个方法:

- (void)layoutSubviews
{
    [super layoutSubviews];
    CGSize mysize = [self intrinsicContentSize];
    CGRect frame = _titleLabel.frame;
    // center in the view
    frame.origin.x = (mysize.width - [_titleLabel intrinsicContentSize].width) / 2;
    frame.origin.y = 0;
    frame.size.width = [_titleLabel intrinsicContentSize].width;
    frame.size.height = [_titleLabel intrinsicContentSize].height;
    _titleLabel.frame = frame;
    _titleLabel.backgroundColor = [UIColor redColor];
}

我认为这不是一个好主意,因为方法layoutSubviews将被多次调用。当我在此处设置文本时,它无法调整视图大小:

- (void)viewWillAppear:(BOOL)animated
{
    // the view can be resized
    _avartarView.titleLabel.text = @"asdfjkl;!@#$%^&*()";
}

- (void)viewDidAppear:(BOOL)animated
{
    // the view cannot be resize
    _avartarView.titleLabel.text = @"haha";
}

有没有解决方案?

我已尝试使用自动布局,但它不起作用。 avartarView的高度仍为零。

@implementation ViewController

- (void)viewDidLoad
{
[super viewDidLoad];

_avartarView = [[PPAvartarView alloc] init];
_avartarView.backgroundColor = [UIColor yellowColor];
_avartarView.titleLabel.text = @"foobar";
_avartarView.titleLabel.textColor = [UIColor blackColor];
_avartarView.translatesAutoresizingMaskIntoConstraints = NO;
[self.view addSubview: _avartarView];
[self.view addConstraints: [NSLayoutConstraint constraintsWithVisualFormat: @"H:|-50-[_avartarView]" options: 0 metrics: nil views: NSDictionaryOfVariableBindings(_avartarView)]];
[self.view addConstraints: [NSLayoutConstraint constraintsWithVisualFormat: @"V:|-100-[_avartarView]" options: 0 metrics: nil views: NSDictionaryOfVariableBindings(_avartarView)]];
_avartarView.backgroundColor = [UIColor redColor];
}

@end


@implementation PPAvartarView

- (id)init
{
self = [super init];
_titleLabel = [[UILabel alloc] init];
_titleLabel.translatesAutoresizingMaskIntoConstraints = NO;
[self addSubview: _titleLabel];
[self addConstraints: [NSLayoutConstraint constraintsWithVisualFormat: @"V:|-10-[_titleLabel]-10-|" options: 0 metrics: nil views: NSDictionaryOfVariableBindings(_titleLabel)]];
[self addConstraint: [NSLayoutConstraint constraintWithItem: _titleLabel attribute: NSLayoutAttributeCenterX relatedBy: NSLayoutRelationEqual toItem: self attribute: NSLayoutAttributeCenterX multiplier: 1 constant: 0]];
return self;
}

@end

0 个答案:

没有答案