#import <UIKit/UIKit.h>
@interface ActiveLabel : UILabel
//记录行数
@property (nonatomic , assign) int rows;
//设置伸缩
- (void)setTheContraction:(BOOL)whether;
@end
-------------------------------
#import "ActiveLabel.h"
@interface ActiveLabel ()
{
CGFloat width;
CGFloat x;
CGFloat y;
CGFloat height;
}
@end
@implementation ActiveLabel
- (void)setFrame:(CGRect)frame{
[super setFrame:frame];
width = frame.size.width;
x = frame.origin.x;
y = frame.origin.y;
self.numberOfLines = 0;
}
- (void)setText:(NSString *)text{
[super setText:text];
NSDictionary * dict = @{
NSFontAttributeName : self.font
};
CGSize size = [text boundingRectWithSize:CGSizeMake(width, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin attributes:dict context:nil].size;
//显示全部高度
// self.frame = CGRectMake(x, y, width, size.height);
self.frame = CGRectMake(x, y, width, self.font.lineHeight);
CGFloat labelHeight = [self sizeThatFits:CGSizeMake(width, MAXFLOAT)].height;
CGFloat count = (labelHeight) / self.font.lineHeight;
height = size.height;
self.rows = count;
}
- (void)setTheContraction:(BOOL)whether{
//
if (!whether) {
self.frame = CGRectMake(x, y, width, self.font.lineHeight);
}else{
self.frame = CGRectMake(x, y, width, height);
}
}
@end
=======================================================
用法:
#import "ViewController.h"
#import "ActiveLabel.h"
#define KWidth [UIScreen mainScreen].bounds.size.width
@interface ViewController ()
@property (nonatomic,strong) ActiveLabel * label;
@property (nonatomic , strong) UIFont * font;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
self.label = [[ActiveLabel alloc] initWithFrame:CGRectMake(10, 100, KWidth - 20, MAXFLOAT)];
self.font = [UIFont systemFontOfSize:17];
self.label.backgroundColor = [UIColor redColor];
[self.view addSubview:self.label];
self.label.text = @"Do any additional setup after loading the view, typically from a nib,Do any additional setup after loading the view, typically from a nib,Do any additional setup after loading the view, typically from a nib";
UIButton * btn = [UIButton buttonWithType:(UIButtonTypeCustom)];
btn.frame = CGRectMake(KWidth - 80, 40, 60, 30);
[btn setTitle:@"收展" forState:(UIControlStateNormal)];
[btn setBackgroundColor:[UIColor grayColor]];
[self.view addSubview:btn];
[btn addTarget:self action:@selector(shrinkageAction:) forControlEvents:(UIControlEventTouchUpInside)];
NSLog(@"rows === %d",self.label.rows);
}
- (void)shrinkageAction:(UIButton *)sender{
sender.selected = !sender.selected;
[self.label setTheContraction:sender.selected];
}