Skip to content

Instantly share code, notes, and snippets.

@J-ogawa
Last active August 29, 2015 13:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save J-ogawa/9976186 to your computer and use it in GitHub Desktop.
Save J-ogawa/9976186 to your computer and use it in GitHub Desktop.
//
// UIView+adjustText.m
//
// Created by J_ogawa on 2014/04/04.
// Copyright (c) 2014年 J_ogawa. All rights reserved.
//
#import "UIView+adjustTextLabel.h"
@implementation UIView (adjustTextLabel)
- (id)initWithFrame:(CGRect)frame
text:(id)text
padding:(CGFloat)padding
maxHeight:(CGFloat)maxHeight
templateLabel:(UILabel *)templateLabel
{
BOOL isAttributed;
if ([text isKindOfClass:[NSString class]]) {
isAttributed = NO;
} else if ([text isKindOfClass:[NSAttributedString class]]) {
isAttributed = YES;
} else {
return nil;
}
CGSize constraint = CGSizeMake(frame.size.width - (2 * padding), (maxHeight) ? MIN(maxHeight, 20000.0f) : 20000.0f);
UILabel *label = (templateLabel) ? templateLabel : [UILabel new];
CGSize size = isAttributed ? [self sizeOfAttrStr:text constraint:constraint] : [self sizeOfStr:text constraint:constraint font:label.font];
label.frame = CGRectMake(padding, padding, size.width, size.height);
[label setLineBreakMode:NSLineBreakByWordWrapping];
[label setNumberOfLines:0];
if (isAttributed) {
label.attributedText = text;
} else {
label.text = text;
}
CGRect viewFrame = CGRectMake(frame.origin.x, frame.origin.y, frame.size.width, size.height + padding * 2);
self = [self initWithFrame:viewFrame];
if (self) {
[self addSubview:label];
}
return self;
}
- (CGSize)sizeOfStr:(NSString *)str constraint:(CGSize)constraint font:(UIFont *)font
{
CGSize size = [str boundingRectWithSize:constraint options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:font} context:nil].size;
return (CGSize){ ceil(size.width), ceil(size.height) };
}
- (CGSize)sizeOfAttrStr:(NSAttributedString *)attrStr constraint:(CGSize)constraint
{
CGSize size = [attrStr boundingRectWithSize:constraint options:NSStringDrawingUsesLineFragmentOrigin context:nil].size;
return (CGSize){ ceil(size.width), ceil(size.height) };
}
@end
@J-ogawa
Copy link
Author

J-ogawa commented Apr 4, 2014

create view which have flexible height label with text length (attribute).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment