你的位置:首页 > 操作系统

[操作系统]你真的了解UIButton、UILabel 吗?


一:首先查看一下关于UIButton的定义

@class UIImage, UIFont, UIColor, UIImageView, UILabel;//设置UIButton的样式typedef NS_ENUM(NSInteger, UIButtonType) {  UIButtonTypeCustom = 0,             // 自定义,无风格  UIButtonTypeSystem NS_ENUM_AVAILABLE_IOS(7_0), // standard system button  UIButtonTypeDetailDisclosure, //蓝色的披露按钮,可放在任何文字旁  UIButtonTypeInfoLight, //微件(widget)使用的小圆圈信息按钮,可以放在任何文字旁  UIButtonTypeInfoDark, //白色背景下使用的深色圆圈信息按钮  UIButtonTypeContactAdd, //蓝色加号(+)按钮,可以放在任何文字旁    UIButtonTypeRoundedRect = UIButtonTypeSystem,  // 白色圆角矩形,类似偏好设置表格单元或者地址簿卡片};NS_CLASS_AVAILABLE_IOS(2_0) @interface UIButton : UIControl <NSCoding>+ (instancetype)buttonWithType:(UIButtonType)buttonType;@property(nonatomic)     UIEdgeInsets contentEdgeInsets UI_APPEARANCE_SELECTOR; // 默认值 UIEdgeInsetsZero 所有按钮的内容周围的矩形的内侧或者外侧的边缘@property(nonatomic)     UIEdgeInsets titleEdgeInsets;        // 默认值UIEdgeInsetsZero 设置文字的EdgeInsets 在按钮标题文本周围矩形的,向内或者向外的边缘@property(nonatomic)     BOOL     reversesTitleShadowWhenHighlighted; // 默认值NO.当按钮高亮时,是否更改标题阴影@property(nonatomic)     UIEdgeInsets imageEdgeInsets;        // 默认值 UIEdgeInsetsZero 设置UIButton上的图标间距 属于按钮图片周围矩形的,向内或者向外的边缘@property(nonatomic)     BOOL     adjustsImageWhenHighlighted;  // 默认值为YES.默认情况下,在按钮被禁用时,图像会被画的颜色深一些。要禁用此功能,请将这个属性设置为NO:@property(nonatomic)     BOOL     adjustsImageWhenDisabled;    // 默认值为YES.默认情况下,按钮在被禁用时,图像会被画的颜色淡一些。要禁用此功能,请将这个属性设置为NO:@property(nonatomic)     BOOL     showsTouchWhenHighlighted;   // 默认值为 NO. 这个属性设置为YES,可令按钮在按下时发光@property(null_resettable, nonatomic,strong)  UIColor   *tintColor NS_AVAILABLE_IOS(5_0); // The tintColor is inherited through the superview hierarchy. See UIView for more information.//获取当前UIButton的UIButtonType 只读@property(nonatomic,readonly) UIButtonType buttonType;//常见的设置属性效果- (void)setTitle:(nullable NSString *)title forState:(UIControlState)state;          - (void)setTitleColor:(nullable UIColor *)color forState:(UIControlState)state UI_APPEARANCE_SELECTOR; - (void)setTitleShadowColor:(nullable UIColor *)color forState:(UIControlState)state UI_APPEARANCE_SELECTOR; - (void)setImage:(nullable UIImage *)image forState:(UIControlState)state;           - (void)setBackgroundImage:(nullable UIImage *)image forState:(UIControlState)state UI_APPEARANCE_SELECTOR; - (void)setAttributedTitle:(nullable NSAttributedString *)title forState:(UIControlState)state NS_AVAILABLE_IOS(6_0); // default is nil. title is assumed to be single line- (nullable NSString *)titleForState:(UIControlState)state;   - (nullable UIColor *)titleColorForState:(UIControlState)state;- (nullable UIColor *)titleShadowColorForState:(UIControlState)state;- (nullable UIImage *)imageForState:(UIControlState)state;- (nullable UIImage *)backgroundImageForState:(UIControlState)state;- (nullable NSAttributedString *)attributedTitleForState:(UIControlState)state NS_AVAILABLE_IOS(6_0);//获取当前UIButton的一些属性值 都为只读@property(nullable, nonatomic,readonly,strong) NSString *currentTitle;       // normal/highlighted/selected/disabled. can return nil@property(nonatomic,readonly,strong) UIColor *currentTitleColor;    // normal/highlighted/selected/disabled. always returns non-nil. default is white(1,1)@property(nullable, nonatomic,readonly,strong) UIColor *currentTitleShadowColor; // normal/highlighted/selected/disabled.@property(nullable, nonatomic,readonly,strong) UIImage *currentImage;       // normal/highlighted/selected/disabled. can return nil@property(nullable, nonatomic,readonly,strong) UIImage *currentBackgroundImage;  // normal/highlighted/selected/disabled. can return nil@property(nullable, nonatomic,readonly,strong) NSAttributedString *currentAttributedTitle NS_AVAILABLE_IOS(6_0); // normal/highlighted/selected/disabled. can return nil@property(nullable, nonatomic,readonly,strong) UILabel   *titleLabel NS_AVAILABLE_IOS(3_0);@property(nullable, nonatomic,readonly,strong) UIImageView *imageView NS_AVAILABLE_IOS(3_0);//指定背景边界- (CGRect)backgroundRectForBounds:(CGRect)bounds;//指定内容边界- (CGRect)contentRectForBounds:(CGRect)bounds;//指定文字标题边界- (CGRect)titleRectForContentRect:(CGRect)contentRect;//指定按钮图像边界- (CGRect)imageRectForContentRect:(CGRect)contentRect;@end

UIButton是继承于UIControl,并且也遵循NSCoding的协议;

知识点1:关于UIControlState的Enum值

enum{UIControlStateNormal       = 0,//常态UIControlStateHighlighted  = 1 << 0,//高亮UIControlStateDisabled     = 1 << 1,//禁用UIControlStateSelected     = 1 << 2,//选中UIControlStateApplication  = 0x00FF0000,//当应用程序标志使用时UIControlStateReserved     = 0xFF000000//为内部框架预留的};typedef NSUInteger UIControlState;

知识点2:contentHorizontalAlignment;可以设置UIButton文字的对齐方式,contentHorizontalAlignment并不是UIButton的属性,而是它父类UIControl的一个属性;

typedef NS_ENUM(NSInteger, UIControlContentHorizontalAlignment) {  UIControlContentHorizontalAlignmentCenter = 0,  UIControlContentHorizontalAlignmentLeft  = 1,  UIControlContentHorizontalAlignmentRight = 2,  UIControlContentHorizontalAlignmentFill  = 3,};

知识点3:forControlEvents参数类型

typedef NS_OPTIONS(NSUInteger, UIControlEvents){UIControlEventTouchDown                 = 1 <<  0,//单点触摸按下事件:用户点触屏幕,或者又有新手指落下的时候。UIControlEventTouchDownRepeat      = 1 <<  1,//多点触摸按下事件,点触计数大于1:用户按下第二、三、或第四根手指的时候。UIControlEventTouchDragInside         = 1 <<  2,//当一次触摸在控件窗口内拖动时。UIControlEventTouchDragOutside       = 1 <<  3,//当一次触摸在控件窗口之外拖动时。UIControlEventTouchDragEnter           = 1 <<  4,//当一次触摸从控件窗口之外拖动到内部时UIControlEventTouchDragExit             = 1 <<  5,//当一次触摸从控件窗口内部拖动到外部时。UIControlEventTouchUpInside            = 1 <<  6,//所有在控件之内触摸抬起事件UIControlEventTouchUpOutside          = 1 <<  7,//所有在控件之外触摸抬起事件(点触必须开始与控件内部才会发送通知)。UIControlEventTouchCancel                = 1 <<  8,//所有触摸取消事件,即一次触摸因为放上了太多手指而被取消,或者被上锁或者电话呼叫打断。UIControlEventValueChanged             = 1 << 12,//当控件的值发生改变时,发送通知。用于滑块、分段控件、以及其他取值的控件。你可以配置滑块控件何时发送通知,在滑块被放下时发送,或者在被拖动时发送。UIControlEventEditingDidBegin           = 1 << 16,//当文本控件中开始编辑时发送通知UIControlEventEditingChanged           = 1 << 17,//当文本控件中的文本被改变时发送通知。UIControlEventEditingDidEnd              = 1 << 18,//当文本控件中编辑结束时发送通知。UIControlEventEditingDidEndOnExit    = 1 << 19,//当文本控件内通过按下回车键(或等价行为)结束编辑时,发送通知。UIControlEventAllTouchEvents             = 0x00000FFF,//通知所有触摸事件。UIControlEventAllEditingEvents           = 0x000F0000,//通知所有关于文本编辑的事件。UIControlEventApplicationReserved    = 0x0F000000,//range available for application useUIControlEventSystemReserved          = 0xF0000000,//range reserved for internal framework useUIControlEventAllEvents                      = 0xFFFFFFFF//通知所有事件};

 

二:首先查看一下关于UILabel 的定义

@class UIColor, UIFont;NS_CLASS_AVAILABLE_IOS(2_0) @interface UILabel : UIView <NSCoding>@property(nullable, nonatomic,copy)  NSString      *text;      // 设置文本内容@property(null_resettable, nonatomic,strong) UIFont   *font;      // 设置文本字体,默认是系统17@property(null_resettable, nonatomic,strong) UIColor   *textColor;    // 设置文本色@property(nullable, nonatomic,strong) UIColor      *shadowColor;   // 设置文本的阴影@property(nonatomic)    CGSize       shadowOffset;  // 默认值CGSizeMake(0, -1) @property(nonatomic)    NSTextAlignment  textAlignment;  // 默认值 NSTextAlignmentLeft 文字位置排版@property(nonatomic)    NSLineBreakMode  lineBreakMode;  // default is NSLineBreakByTruncatingTail. used for single and multiple lines of text// 富文本属性@property(nullable, nonatomic,copy)  NSAttributedString *attributedText NS_AVAILABLE_IOS(6_0); // 默认值 nil@property(nullable, nonatomic,strong)        UIColor *highlightedTextColor; // 默认值 nil@property(nonatomic,getter=isHighlighted) BOOL   highlighted;     // 默认值 NO@property(nonatomic,getter=isUserInteractionEnabled) BOOL userInteractionEnabled; // 默认值为 NO 所以它没有点击事件效果@property(nonatomic,getter=isEnabled)        BOOL enabled;         // 默认值为YES.//行数 0表示不限制@property(nonatomic) NSInteger numberOfLines;@property(nonatomic) BOOL adjustsFontSizeToFitWidth;     // 默认值为 NO 文字的大小是否根据宽度来自动调整@property(nonatomic) UIBaselineAdjustment baselineAdjustment; // default is UIBaselineAdjustmentAlignBaselines@property(nonatomic) CGFloat minimumScaleFactor NS_AVAILABLE_IOS(6_0); // default is 0.0@property(nonatomic) BOOL allowsDefaultTighteningForTruncation NS_AVAILABLE_IOS(9_0); // default is NO//重写UILabel布局- (CGRect)textRectForBounds:(CGRect)bounds limitedToNumberOfLines:(NSInteger)numberOfLines;- (void)drawTextInRect:(CGRect)rect;//这个属性是用来设置多行label的最大宽度的//当自动布局的时候约束这个label的时候这个属性会起作用//在自动布局添加约束中,若文本超过了指定的最大宽度的时候 文本会另起一行 从而增加了label的高度@property(nonatomic) CGFloat preferredMaxLayoutWidth NS_AVAILABLE_IOS(6_0);// IOS7以后就弃用@property(nonatomic) CGFloat minimumFontSize NS_DEPRECATED_IOS(2_0, 6_0); // deprecated - use minimumScaleFactor. default is 0.0// IOS7以后就弃用@property(nonatomic) BOOL adjustsLetterSpacingToFitWidth NS_DEPRECATED_IOS(6_0,7_0);@end

UILabel是继承于UIView,并且也遵循NSCoding的协议;

知识点1:枚举类型 默认是NSLineBreakByTruncatingTail

NSLineBreakByWordWrapping = 0, 按着一个单词来显示 不会被剪辑剩余的不会被显示NSLineBreakByCharWrapping,   按着一个字体来显示 不会被剪辑剩余的不会被显示NSLineBreakByClipping,         把能显示的全显示完 剩下的直接不显示可能有的字显示一半就被剪辑NSLineBreakByTruncatingHead,   在那一行显示不全的话 那一行 就以 ...abcd模式来显示NSLineBreakByTruncatingTail,   在那一行显示不全的话 那一行 就以 abcd...模式来显示NSLineBreakByTruncatingMiddle 在那一行显示不全的话那一行 就以 ab...cd模式来显示

知识点2:textAlignment是设置label的对齐方式是一个枚举,默认是左对齐

NSTextAlignmentLeft=0     左对齐NSTextAlignmentCenter=1    居中NSTextAlignmentRight=2     右对齐NSTextAlignmentJustified=3 左右两边都对齐 一个段落的最后一行是natural-alignedNSTextAlignmentNatural=4   显示脚本的默认对齐方式

知识点3:全部NSMutableAttributedString属性

  NSFontAttributeName;         //字体,value是UIFont对象  NSParagraphStyleAttributeName;    //绘图的风格(居中,换行模式,间距等诸多风格),value是NSParagraphStyle对象  NSForegroundColorAttributeName;    // 文字颜色,value是UIFont对象  NSBackgroundColorAttributeName;    // 背景色,value是UIFont  NSLigatureAttributeName;       // 字符连体,value是NSNumber  NSKernAttributeName;         // 字符间隔  NSStrikethroughStyleAttributeName;  //删除线,value是NSNumber  NSUnderlineStyleAttributeName;    //下划线,value是NSNumber  NSStrokeColorAttributeName;      //描绘边颜色,value是UIColor  NSStrokeWidthAttributeName;      //描边宽度,value是NSNumber  NSShadowAttributeName;        //阴影,value是NSShadow对象  NSTextEffectAttributeName;      //文字效果,value是NSString  NSAttachmentAttributeName;      //附属,value是NSTextAttachment 对象  NSLinkAttributeName;         //链接,value是NSURL or NSString  NSBaselineOffsetAttributeName;    //基础偏移量,value是NSNumber对象  NSUnderlineColorAttributeName;    //下划线颜色,value是UIColor对象  NSStrikethroughColorAttributeName;  //删除线颜色,value是UIColor  NSObliquenessAttributeName;      //字体倾斜  NSExpansionAttributeName;       //字体扁平化  NSVerticalGlyphFormAttributeName;   //垂直或者水平,value是 NSNumber,0表示水平,1垂直

实例运用:

/************************************************某区域内************************************************************/NSMutableAttributedString *string = [[NSMutableAttributedString alloc]initWithString:@"0元"]; [string setAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:14]} range:NSMakeRange(string.length-1, 1)]; etlbl.attributedText = string;/************************************************基本用法************************************************************/  NSString *content = @"内容太多,需要自适应才能解决问题,所以需要写这个扩展类,内容太多,需要自适应才能解决问题,所以需要写这个扩展类";  NSMutableAttributedString *string = [[NSMutableAttributedString alloc]initWithString:content];  //字体大小  [string addAttribute:NSFontAttributeName          value:[UIFont systemFontOfSize:10]          range:NSMakeRange(0, 1)];  //字体颜色  [string addAttribute:NSForegroundColorAttributeName          value:[UIColor yellowColor]          range:NSMakeRange(1, 1)];  //字体背景颜色  [string addAttribute:NSBackgroundColorAttributeName          value:[UIColor purpleColor]          range:NSMakeRange(2, 1)];  //添加下划线  [string addAttribute:NSUnderlineStyleAttributeName          value:@(NSUnderlineStyleSingle)          range:NSMakeRange(3, 1)];  //添加下划线颜色  [string addAttribute:NSUnderlineColorAttributeName          value:[UIColor redColor]          range:NSMakeRange(3, 1)];  UILabel *etlbl3 = [[UILabel alloc]initWithFrame:CGRectMake(100, 400, 200, 30)];  etlbl3.attributedText = string;  [self.view addSubview:etlbl3];

知识点4:iOS的UILabel设置居上对齐,居中对齐,居下对齐

在iOS中默认的UILabel中的文字在竖直方向上只能居中对齐,从UILabel继承了一个新类,实现了居上对齐,居中对齐,居下对齐。

#import <UIKit/UIKit.h> typedef enum {   VerticalAlignmentTop = 0, // default   VerticalAlignmentMiddle,   VerticalAlignmentBottom, } VerticalAlignment; @interface myUILabel : UILabel { @private VerticalAlignment _verticalAlignment; }  @property (nonatomic) VerticalAlignment verticalAlignment;  @end 

#import "myUILabel.h"  @implementation myUILabel @synthesize verticalAlignment = verticalAlignment_;  - (id)initWithFrame:(CGRect)frame {   if (self = [super initWithFrame:frame]) {     self.verticalAlignment = VerticalAlignmentMiddle;   }   return self; }  - (void)setVerticalAlignment:(VerticalAlignment)verticalAlignment {   verticalAlignment_ = verticalAlignment;   [self setNeedsDisplay]; }  - (CGRect)textRectForBounds:(CGRect)bounds limitedToNumberOfLines:(NSInteger)numberOfLines {   CGRect textRect = [super textRectForBounds:bounds limitedToNumberOfLines:numberOfLines];   switch (self.verticalAlignment) {     case VerticalAlignmentTop:       textRect.origin.y = bounds.origin.y;       break;     case VerticalAlignmentBottom:       textRect.origin.y = bounds.origin.y + bounds.size.height - textRect.size.height;       break;     case VerticalAlignmentMiddle:       // Fall through.     default:       textRect.origin.y = bounds.origin.y + (bounds.size.height - textRect.size.height) / 2.0;   }   return textRect; }  -(void)drawTextInRect:(CGRect)requestedRect {   CGRect actualRect = [self textRectForBounds:requestedRect limitedToNumberOfLines:self.numberOfLines];   [super drawTextInRect:actualRect]; }   @end 

运用(实现左上的效果):

lbl_mylabel = [[myUILabel alloc] initWithFrame:CGRectMake(20, 50, 150, 600)]; UIColor *color = [UIColor colorWithPatternImage:[UIImage imageNamed:@"halfTransparent.png"]];//使用半透明图片作为label的背景色 lbl_mylabel.backgroundColor = color; lbl_mylabel.textAlignment = UITextAlignmentLeft; lbl_mylabel.textColor = UIColor.whiteColor; lbl_mylabel.lineBreakMode = UILineBreakModeWordWrap; lbl_mylabel.numberOfLines = 0; [lbl_mylabel setVerticalAlignment:VerticalAlignmentTop]; [self addSubview:lbl_mylabel]; 

上面的实例就是针对下面两个方法的运用:

- (CGRect)textRectForBounds:(CGRect)bounds limitedToNumberOfLines:(NSInteger)numberOfLines;- (void)drawTextInRect:(CGRect)rect;