标签:
//
// ChatBubble.h
// ChatBubble
//
// Created by 大欢 on 16/1/21.
// Copyright © 2016年 bjsxt. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface ChatBubble : UIImageView
//显示的文字
@property (nonatomic, copy) NSString * text;
@end
/******************************************/
//
// ChatBubble.m
// ChatBubble
//
// Created by 大欢 on 16/1/21.
// Copyright © 2016年 bjsxt. All rights reserved.
//
#import "ChatBubble.h"
//文字距图片左边距
static const CGFloat kLeftMargin = 20;
//文字距图片上,下,右边距
static const CGFloat kOtherMargin = 10;
@interface ChatBubble ()
@property (nonatomic, strong) UILabel * textLabel;
@end
@implementation ChatBubble
- (UILabel *)textLabel {
if (!_textLabel) {
_textLabel = [[UILabel alloc] init];
_textLabel.font = [UIFont systemFontOfSize:17];
_textLabel.textColor = [UIColor blackColor];
_textLabel.numberOfLines = 0;
}
return _textLabel;
}
- (instancetype)initWithFrame:(CGRect)frame {
if (self = [super initWithFrame:frame]) {
//拉伸图片
self.image = [UIImage imageNamed:@"qipao"];
self.image = [self.image resizableImageWithCapInsets:UIEdgeInsetsMake(25, 15, 5, 5) resizingMode:UIImageResizingModeStretch];
//加载label
[self addSubview:self.textLabel];
}
return self;
}
- (void)setText:(NSString *)text {
_text = text;
_textLabel.text = text;
}
- (CGSize)sizeThatFits:(CGSize)size {
//计算Label的宽度
CGFloat width = size.width - kLeftMargin - kOtherMargin;
//根据Label的宽度计算出Label的高度
CGSize sizeLabel = [_textLabel sizeThatFits:CGSizeMake(width, MAXFLOAT)];
//设置Label的frame
_textLabel.frame = CGRectMake(kLeftMargin, kOtherMargin, sizeLabel.width, sizeLabel.height);
CGFloat imageWidth = size.width;
//计算imageview的高度
CGFloat imageHeight = kOtherMargin * 2 + _textLabel.frame.size.height;
return CGSizeMake(imageWidth, imageHeight);
}
@end
/************************************************************/
//
// ViewController.m
// ChatBubble
//
// Created by 大欢 on 16/1/21.
// Copyright © 2016年 bjsxt. All rights reserved.
//
#import "ViewController.h"
#import "ChatBubble.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
CGFloat width = self.view.frame.size.width - 60;
ChatBubble * bubble = [[ChatBubble alloc] init];
bubble.text = @"初期投资66亿美元,最终长度为400英里,总投资330亿美元,折合每英里8250万美元。而超级高铁项目建设成本约为每英里2000万美元,??";
CGSize size = [bubble sizeThatFits:CGSizeMake(width, MAXFLOAT)];
bubble.frame = CGRectMake(20, 30, size.width, size.height);
[self.view addSubview:bubble];
}
@end
/******************************************************/
标签:
原文地址:http://www.cnblogs.com/MrWuYindi/p/5149928.html