我正在尝试这个自定义类 - TMQuiltView - https://github.com/1000Memories/TMQuiltView。通常,我在Storyboard中布局界面,这不是问题。由于这是一个自定义类,看起来好像我必须以编程方式这样做。
我会发布他们演示中的内容的截图,但我没有足够的声誉。相反,我将展示 - (void)layoutSubviews方法
- (void)layoutSubviews {
self.photoView.frame = CGRectInset(self.bounds, kTMPhotoQuiltViewMargin, kTMPhotoQuiltViewMargin);
self.titleLabel.frame = CGRectMake(kTMPhotoQuiltViewMargin, self.bounds.size.height - 20 - kTMPhotoQuiltViewMargin, self.bounds.size.width - 2 * kTMPhotoQuiltViewMargin, 20);
}
我的目标是让titleLabel出现在photoView下方,但我不希望它是一个明确的大小(即如果我是故事板,我会使用autolayout)。所以,在titleLabel的方法中,我试图计算标签的高度:
CGSize labelSize = [_titleLabel.text sizeWithFont:_titleLabel.font
constrainedToSize:_titleLabel.frame.size
lineBreakMode:NSLineBreakByWordWrapping];
labelHeight = labelSize.height;
但是这里我正陷入死胡同。我不能用它来制作CGRect(CGPoint是不兼容的)。我是否在某处为图像制作了CGRect?如何根据self.bounds定义它?
答案 0 :(得分:0)
[super layoutSubviews];
方法中致电layoutSubviews
。sizeWithFont:constrainedToSize:lineBreakMode:
_titleLabel.lineBreakMode
Ofc你可以在你的方法中使用这个大小,例如通过:
CGRectMake(origin.x, origin.y, size.width, size.height);
为了帮助您对其进行编码,我需要澄清一下:您想要一个高于标签的imageView,标签应根据文字大小调整大小?
Ad3的。您可以使用此类方法(来源:GitHub opensource library):
- (CGSize)ios67sizeWithFont:(UIFont *)font constrainedToSize:(CGSize)size {
CGSize textSize;
if ([self respondsToSelector:@selector(boundingRectWithSize:options:attributes:context:)]) {
textSize = [self boundingRectWithSize:size options:(NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading) attributes:@{NSFontAttributeName:font} context:nil].size;
} else {
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
textSize = [self sizeWithFont:font constrainedToSize:size];
#pragma clang diagnostic pop
}
return textSize;
}