【问题标题】:layoutSubviews Confusion — Manipulating TMQuiltViewlayoutSubviews 混乱——操作 TMQuiltView
【发布时间】:2014-11-20 10:42:04
【问题描述】:

我正在试用这个自定义类 - 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 下方,但我不希望它具有确定的大小(即,如果我是故事板,我会使用自动布局)。于是,在titleLabel的方法中,我尝试计算了标签的高度:

CGSize labelSize = [_titleLabel.text sizeWithFont:_titleLabel.font
                                constrainedToSize:_titleLabel.frame.size
                                    lineBreakMode:NSLineBreakByWordWrapping];

    labelHeight = labelSize.height;

但这就是我陷入死胡同的地方。我不能在制作 CGRect 时使用它(CGPoint 不兼容)。我在某处为图像制作 CGRect 吗?我如何定义它与 self.bounds 的关系?

【问题讨论】:

    标签: ios objective-c xcode layoutsubviews


    【解决方案1】:
    1. 别忘了在layoutSubviews方法中调用[super layoutSubviews];
    2. sizeWithFont:constrainedToSize:lineBreakMode: 在 iOS8 中已弃用
    3. 您可以在计算方法中使用_titleLabel.lineBreakMode

    你可以在你的方法中使用这个尺寸,例如通过:

    CGRectMake(origin.x, origin.y, size.width, size.height);
    

    为了帮助您编写代码,我需要澄清一下:您想要一个位于标签上方的 imageView,并且标签应根据文本大小调整大小?

    广告 3。您可以改用这种方法(来源: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;
    }
    

    【讨论】:

    • 感谢您的回复。假设定义了 textSize。如何创建正确的矩形。对于 imageView,有 CGRectInset(self.bounds, kTMPhotoQuiltViewMargin, kTMPhotoQuiltViewMargin);标题标签呢? CGRectMake(kTMPhotoQuiltMargin, 图像底部 + 2, size.width, size.height)?如何获得图像底部?
    • CGRect imageViewRect = CGRectInset(self.bounds, kTMPhotoQuiltViewMargin, kTMPhotoQuiltViewMargin); CGRect titleLabelRect = CGRectMake(CGRectGetMinX(imageViewRect), CGRectGetMaxY(imageViewRect) + myMargin, textSize.width, textSize.height);
    • 好的。我似乎快到了。我会继续玩,直到我得到我想要的结果,但你的回答在此期间有所帮助。谢谢!
    • 没问题 :) 如果对你有帮助,请采纳答案 ;)
    猜你喜欢
    • 2011-07-19
    • 2023-04-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-02-10
    相关资源
    最近更新 更多