这篇文章两个重点:
1、自定义可复制内容的label
2、介绍iOS7以后根据字符串计算label宽度的方法
一、自定义可复制内容的label
定义VCCopyLabel集成UILabel,其余一切尽在注释中。
#import "VCCopyLabel.h"
@implementation VCCopyLabel
//让label有资格成为第一响应者
- (BOOL)canBecomeFirstResponder{
return YES;
}
/*
以下是系统默认的 UIMenuItem 所对应的 action ,这里只设置了拷贝
cut: // 剪切
copy: // 拷贝
select: // 选择
selectAll: // 全选
paste: // 粘贴
delete: // 删除
*/
//重写此方法,来控制 UIMenuItem 的显示和隐藏
- (BOOL)canPerformAction:(SEL)action withSender:(id)sender{
return action == @selector(copy:);
}
//重写copy方法
- (void)copy:(id)sender{
//获取粘贴板
UIPasteboard *pasteBoard = [UIPasteboard generalPasteboard];
//只获取数字
NSCharacterSet* nonDigits =[[NSCharacterSet decimalDigitCharacterSet] invertedSet];
NSInteger num =[[self.text stringByTrimmingCharactersInSet:nonDigits] integerValue];
pasteBoard.string = [NSString stringWithFormat:@"%zd",num];
//获取全部内容的话可以用这句
//pasteBoard.string = self.text ;
}
//UILabel默认不响应事件,自己添加事件。
- (void)attachTapHandler{
self.userInteractionEnabled = YES;
UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(handleTap:)];
if(![self.gestureRecognizers containsObject:longPress]){
[self addGestureRecognizer:longPress];
}
}
//手动创建绑定事件
- (instancetype)initWithFrame:(CGRect)frame{
if(self = [super initWithFrame:frame]){
[self attachTapHandler];
}
return self;
}
//xib、storyboard使用label绑定事件
- (void)awakeFromNib{
[super awakeFromNib];
[self attachTapHandler];
}
//label的长按事件
- (void)handleTap:(UIGestureRecognizer *)gestureRecognizer{
if (gestureRecognizer.state != UIGestureRecognizerStateBegan) {
return;
}
[self becomeFirstResponder];
[[UIMenuController sharedMenuController] setTargetRect:self.frame inView:self.superview];
[[UIMenuController sharedMenuController] setMenuVisible:YES animated:YES];
// [self copy:self];
// NSDictionary *dict = @{
// @"info":@"订单号复制成功"
// };
// [[NSNotificationCenter defaultCenter]postNotificationName:VANCL_COPY_ORDER_NUMBER_SUCCESS_NOTIFICATION object:nil userInfo:dict];
}
- (void)dealloc{
[[NSNotificationCenter defaultCenter] removeObserver:self];
}
@end
二、根据字符串计算label宽度的方法
先上代码,这个代码是计算出label的frame,然后把label添加到tableViewCell上。
NSString *text = [NSString stringWithFormat:@"订单号:%@",_order.orderId];
UIFont *font = [UIFont systemFontOfSize:14.0f];
NSDictionary *attributes = @{NSFontAttributeName : font};
CGSize textSize = [text boundingRectWithSize:orderCell.bounds.size options:NSStringDrawingUsesLineFragmentOrigin attributes:attributes context:nil].size;
CGFloat X = 15;
CGFloat Y = 0;
CGFloat Width = textSize.width;
CGFloat Height = orderCell.bounds.size.height;
CGRect frame = CGRectMake(X, Y, Width, Height);
VCCopyLabel *label = [[VCCopyLabel alloc] initWithFrame:frame];
label.font = font;
label.text = text;
[orderCell addSubview:label];
这里详细介绍下计算宽度的这个方法
- (CGRect)boundingRectWithSize:(CGSize)size
options:(NSStringDrawingOptions)options
attributes:(nullable NSDictionary<NSString *, id> *)attributes
context:(nullable NSStringDrawingContext *)context
NS_AVAILABLE(10_11, 7_0);
参数介绍:
- size:限制尺寸,用于计算文本绘制时占据的矩形块,一般填写父view的size。也可根据实际情况设置为MAXFLOAT
- option:文本绘制时的附加选项有四种类型:
// The specified origin is the line fragment origin, not the base line origin
// 整个文本将以每行组成的矩形为单位计算整个文本的尺寸
NSStringDrawingUsesLineFragmentOrigin = 1 << 0,
--
// Uses the font leading for calculating line heights
// 使用字体的行间距来计算文本占用的范围,即每一行的底部到下一行的底部的距离计算
NSStringDrawingUsesFontLeading = 1 << 1,
--
// Uses image glyph bounds instead of typographic bounds
// 将文字以图像符号计算文本占用范围,而不是排版的边界
NSStringDrawingUsesDeviceMetrics = 1 << 3,
--
// Truncates and adds the ellipsis character to the last visible line if the text doesn't fit into the bounds specified.
// Ignored if NSStringDrawingUsesLineFragmentOrigin is not also set.
// 如果文本内容超出指定的矩形限制,文本将被截去并在最后一个字符后加上省略号。
// 如果 NSStringDrawingUsesLineFragmentOrigin 没有设置,则该选项不生效
// 使用NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingTruncatesLastVisibleLine 让该枚举类型起作用
NSStringDrawingTruncatesLastVisibleLine NS_ENUM_AVAILABLE(10_5, 6_0) = 1 << 5,
- attributes:将文本字体、字号等属性存入字典传到这里。例如
NSDictionary *dict = @{NSFontAttributeName : font}
- context:上下文。包括一些信息,例如如何调整字间距以及缩放。最终,该对象包含的信息将用于文本绘制。该参数可为 nil 。