0

こんにちは、これらのコードでテキストサイズを再作成しています

CGSize textSize = [self.text sizeWithFont:self.font
                        constrainedToSize:self.frame.size
                            lineBreakMode:self.lineBreakMode];

上記は減価償却費です。目的を維持するためにどのように変更できますか?

どんな助けでも大歓迎です。ありがとう!

私の機能全体の目的は、UIlable の上部 (垂直) を揃えることです。

- (void)alignTop
{
    CGSize textSize = [self.text sizeWithFont:self.font
                            constrainedToSize:self.frame.size
                                lineBreakMode:self.lineBreakMode];

    CGRect textRect = CGRectMake(self.frame.origin.x,
                                 self.frame.origin.y,
                                 self.frame.size.width,
                                 textSize.height);
    [self setFrame:textRect];
    [self setNeedsDisplay];
}
4

1 に答える 1

2

これを使って

 - (CGRect)boundingRectWithSize:(CGSize)size options:(NSStringDrawingOptions)options attributes:(nullable NSDictionary<NSString *, id> *)attributes context:(nullable NSStringDrawingContext *)context

またはこれを使用

 - (CGSize)sizeWithAttributes:(nullable NSDictionary<NSString *, id> *)attrs

これは一例です

+ (CGSize)neededSizeForText:(NSString*)text withFont:(UIFont*)font andMaxWidth:(float)maxWidth
{
    NSStringDrawingOptions options = (NSStringDrawingUsesFontLeading|NSStringDrawingUsesLineFragmentOrigin);

    NSMutableParagraphStyle * style =  [[NSMutableParagraphStyle alloc] init];
    [style setLineBreakMode:NSLineBreakByWordWrapping];
    [style setAlignment:NSTextAlignmentRight];

    NSDictionary *textAttibutes = @{NSFontAttributeName : font,
                                    NSParagraphStyleAttributeName : style};

    CGSize neededTextSize = [text boundingRectWithSize:CGSizeMake(maxWidth, 500) options:options attributes:textAttibutes context:nil].size;

    return neededTextSize;
}

これが役立つことを願っています

于 2016-07-30T15:39:44.683 に答える