前言
UILabel繼承自UIView是iOS中使用非常頻繁的一個視圖控件一般用于顯示文字。
一:基本使用
1.創建
UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(20, 64, 100, 30)];[self.view addSubview:label];
2.屬性設置
在iOS中你想要使用一個屬性一般就直接“.”屬性英文名稱,或者“set”屬性英文名稱一般就可以出現
label.backgroundColor = [UIColor yellowColor];//設置背景顏色label.textColor = [UIColor redColor];//設置Label上文字的顏色label.text = @"我是一個UILabel";//設置Label上的文字label.font = [UIFont systemFontOfSize:15];//設置Label上文字的大小 默認為17label.textAlignment = NSTextAlignmentCenter;//設置文字位子默認靠左label.numberOfLines = 0;//設置行數默認為1,當為0時可以就是設置多行label.font = [UIFont fontWithName:@"Arial" size:30];//設置內容字體和字體大小label.highlighted = YES;//Label是否高亮//有時偶爾會使用到陰影設置label.shadowColor = [UIColor blueColor];//設置陰影顏色label.shadowOffset = CGSizeMake(10, 10);//設置陰影的偏移
二、在iOS中下面三個控件,自身就有復制-粘貼的功能:
1、UITextView
2、UITextField
3、UIWebView
在iOS8 之后, 我們發現UILabel不在為我們提供長按彈出復制等操作了, 我們來繼承UILabel自己寫一個帶復制功能的UILabel
三、廢話少說,直接擼代碼
#import "CopyLabel.h"@implementation CopyLabel- (instancetype)initWithFrame:(CGRect)frame { if (self = [super initWithFrame:frame]) { [self pressAction]; } return self;}// 初始化設置- (void)pressAction { self.userInteractionEnabled = YES; UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(longPressAction:)]; longPress.minimumPressDuration = 0.25; [self addGestureRecognizer:longPress];}// 使label能夠成為響應事件- (BOOL)canBecomeFirstResponder { return YES;}// 自定義方法時才顯示對就選項菜單,即屏蔽系統選項菜單- (BOOL)canPerformAction:(SEL)action withSender:(id)sender { if (action == @selector(customCopy:)){ return YES; } return NO;}- (void)customCopy:(id)sender { UIPasteboard *pasteboard = [UIPasteboard generalPasteboard]; pasteboard.string = self.text;}- (void)longPressAction:(UIGestureRecognizer *)recognizer { if (recognizer.state == UIGestureRecognizerStateBegan) { [self becomeFirstResponder]; UIMenuItem *copyItem = [[UIMenuItem alloc] initWithTitle:@"拷貝" action:@selector(customCopy:)]; UIMenuController *menuController = [UIMenuController sharedMenuController]; menuController.menuItems = [NSArray arrayWithObjects:copyItem, nil]; [menuController setTargetRect:self.frame inView:self.superview]; [menuController setMenuVisible:YES animated:YES]; }}@end
四、廢話少說,直接看效果
- (void)viewDidLoad { [super viewDidLoad]; CopyLabel *copy = [[CopyLabel alloc] initWithFrame:CGRectMake(0, 100, [UIScreen mainScreen].bounds.size.width,50)]; copy.text = @"清明時節雨紛紛,路上行人欲斷魂。"; copy.textAlignment = NSTextAlignmentCenter; copy.backgroundColor = [UIColor yellowColor]; copy.textColor = [UIColor redColor]; copy.font = [UIFont boldSystemFontOfSize:16]; [self.view addSubview:copy];}
五、github地址:
https://github.com/gitwangxiancheng/CopyLabel.git
總結
以上就是這篇文章的全部內容了,希望本文的內容對大家的學習或者工作具有一定的參考學習價值,如果有疑問大家可以留言交流,謝謝大家對VEVB武林網的支持。
新聞熱點
疑難解答