在项目中UIPasteboard的用途
- 在项目中基本都会用到复制, 粘贴, 选择, 全选, 剪切功能.
- UIPasteboard类可以复制字符串, URL, 图片
下面我们就以复制图片为例
效果图1效果图2
- 1 创建一个CopyView类, 继承自UIView
- 2 定义两个UIImageView属性
@interface CopyView ()
@property (strong, nonatomic) UIImageView* img1;
@property (strong, nonatomic) UIImageView* img2;
@end
- 3 开始代码编写
@implementation CopyView
-(UIImageView *)img1{
if (_img1 == nil) {
_img1 = [[UIImageView alloc] initWithFrame:CGRectMake(10.0f, 0.0f, 100.0f, 100.0f)];
_img1.image = [UIImage imageNamed:@"赵雅芝"];
}
return _img1;
}
-(UIImageView *)img2{
if (_img2 == nil) {
_img2 = [[UIImageView alloc] initWithFrame:CGRectMake(CGRectGetMaxX(self.img1.frame)+50.0f, 0.0f, 100.0f, 100.0f)];
_img2.backgroundColor = [UIColor lightGrayColor];
}
return _img2;
}
- (instancetype)initWithFrame:(CGRect)frame {
self = [super initWithFrame:frame];
if (self) {
self.backgroundColor = [UIColor whiteColor];
[self addSubview:self.img1];
[self addSubview:self.img2];
}
return self;
}
- (BOOL)canBecomeFirstResponder {
return YES;
}
- (BOOL)canPerformAction:(SEL)action withSender:(id)sender {
NSArray* methodNameArr = @[@"copy:",@"cut:",@"select:",@"selectAll:",@"paste:"];
if ([methodNameArr containsObject:NSStringFromSelector(action)]) {
return YES;
}
return [super canPerformAction:action withSender:sender];
}
#pragma mark - 复制
- (void)copy:(id)sender {
UIPasteboard* pasteboard = [UIPasteboard generalPasteboard];
[pasteboard setImage:self.img1.image];
}
- (void)paste:(id)sender {
UIPasteboard* pasteboard = [UIPasteboard generalPasteboard];
self.img2.image = [pasteboard image];
}
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
[super touchesBegan:touches withEvent:event];
[self becomeFirstResponder];
UIMenuController *menuController = [UIMenuController sharedMenuController];
[menuController setTargetRect:self.img1.frame inView:self];
[menuController setMenuVisible:YES animated:YES];
}
- 4 使用
- (void)viewDidLoad {
[super viewDidLoad];
CopyView *copyView = [[CopyView alloc] initWithFrame:CGRectMake(20, 80, self.view.bounds.size.width - 40, 100)];
[self.view addSubview:copyView];
}
注意
这时候显示出来的菜单名称是英文
如果要实现中文显示, 请参考(i18n) https://www.jianshu.com/p/cd072583856e
网友评论