標籤:
//
// 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
/******************************************************/
iOS常用技術-氣泡文本自適應