iOS移动开发社区iOS 重修笔记iOS重修

重修笔记之UILabel

2018-02-28  本文已影响10人  iOS_July
NS_CLASS_AVAILABLE_IOS(2_0) @interface UILabel : UIView <NSCoding, UIContentSizeCategoryAdjusting>

一、定义UILabel + 布局

UILabel *lab = [[UILabel alloc]init];
lab.frame = CGRectMake(150, 150, 100, 100);
UILabel *lab = [[UILabel alloc]initWithFrame:CGRectMake(150, 150, 100, 100)];

二、将定义的UILabel添加到父视图上

[self.view addSubview:lab];

三、设置自定义UILabel的各种属性

lab.text = @"一个Label";    
[lab setText:@"一个Label"];
lab.backgroundColor = [UIColor redColor];    
[lab setBackgroundColor:[UIColor redColor]];
//系统字体
lab.font = [UIFont systemFontOfSize:20];    

//设置Arial字体和字体大小    
lab.font = [UIFont fontWithName:@"Arial" size:20];  

//加粗
lab.font = [UIFont boldSystemFontOfSize:20];

//斜体
lab.font = [UIFont italicSystemFontOfSize:20];

//拿到所有字体
NSArray* fonts = [UIFont familyNames];
//通过字体名字设置字体
lab.font = [UIFont fontWithName:[fonts objectAtIndex:1] size:20];
lab.textColor = [UIColor whiteColor];    
lab.textColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"图片名"]];
lab.textAlignment = NSTextAlignmentCenter;
typedef NS_ENUM(NSInteger, NSTextAlignment) {
    NSTextAlignmentLeft      = 0,    // Visually left aligned
#if TARGET_OS_IPHONE
    NSTextAlignmentCenter    = 1,    // Visually centered
    NSTextAlignmentRight     = 2,    // Visually right aligned
#else /* !TARGET_OS_IPHONE */
    NSTextAlignmentRight     = 1,    // Visually right aligned
    NSTextAlignmentCenter    = 2,    // Visually centered
#endif
    NSTextAlignmentJustified = 3,    // Fully-justified. The last line in a paragraph is natural-aligned.
    NSTextAlignmentNatural   = 4,    // Indicates the default alignment for script
} NS_ENUM_AVAILABLE_IOS(6_0);
lab.shadowColor = [UIColor greenColor];
lab.shadowOffset = CGSizeMake(10, 10);
//圆角
lab.layer.cornerRadius = 10;
lab.layer.masksToBounds = YES;

//边框
lab.layer.borderColor = [[UIColor blueColor] CGColor];
lab.layer.borderWidth = 10;
NSString *text = @"我是一段简单富文本";

NSMutableAttributedString *attributeString = [[NSMutableAttributedString alloc] initWithString:text];
    [attributeString setAttributes:@{NSForegroundColorAttributeName : [UIColor yellowColor],   NSFontAttributeName : [UIFont systemFontOfSize:10]} range:NSMakeRange(1, 3)];

lab.attributedText = attributeString;
CGSize size = CGSizeMake(300, 1000);

UIFont *labFont = [UIFont fontWithName:@"Arial" size:20];

CGSize labSize = [lab.text sizeWithFont:labFont constrainedToSize:size];

lab.frame = CGRectMake(0, 150, 300, labSize.height);

四、提示

第一步,定义控件
第二步,将定义的控件添加到视图上
第三步,设置自定义控件的各种属性

但是一般的书写格式是1-3-2:

UILabel *lab = [[UILabel alloc]initWithFrame:CGRectMake(150, 150, 100, 100)];

lab.text = @"一个Label";     
lab.backgroundColor = [UIColor redColor];      
lab.font = [UIFont systemFontOfSize:20];      
lab.textColor = [UIColor whiteColor];      

[self.view addSubview:lab];
上一篇下一篇

猜你喜欢

热点阅读