Last active
August 29, 2015 13:58
-
-
Save J-ogawa/9976186 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// 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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
create view which have flexible height label with text length (attribute).