你真的瞭解UIButton、UILabel 嗎?

你真的瞭解UIbutton,UILabel嗎?

 

一:首先查看一下關於UIButton的定義app

複製代碼
@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的Enumide

複製代碼
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參數類型post

複製代碼
typedef NS_OPTIONS(NSUInteger, UIControlEvents)
{
UIControlEventTouchDown                 = 1 <<  0,//單點觸摸按下事件:用戶點觸屏幕,或者又有新手指落下的時候。
UIControlEventTouchDownRepeat      = 1 <<  1,//多點觸摸按下事件,點觸計數大於1:用戶按下第2、3、或第四根手指的時候。
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 use
UIControlEventSystemReserved          = 0xF0000000,//range reserved for internal framework use
UIControlEventAllEvents                      = 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的協議;atom

知識點1:枚舉類型 默認是NSLineBreakByTruncatingTailspa

NSLineBreakByWordWrapping = 0, 按着一個單詞來顯示 不會被剪輯剩餘的不會被顯示
NSLineBreakByCharWrapping,   按着一個字體來顯示 不會被剪輯剩餘的不會被顯示
NSLineBreakByClipping,         把能顯示的全顯示完 剩下的直接不顯示可能有的字顯示一半就被剪輯
NSLineBreakByTruncatingHead,   在那一行顯示不全的話 那一行 就以 ...abcd模式來顯示
NSLineBreakByTruncatingTail,   在那一行顯示不全的話 那一行 就以 abcd...模式來顯示
NSLineBreakByTruncatingMiddle 在那一行顯示不全的話那一行 就以 ab...cd模式來顯示

知識點2:textAlignment是設置label的對齊方式是一個枚舉,默認是左對齊code

NSTextAlignmentLeft=0     左對齊
NSTextAlignmentCenter=1    居中
NSTextAlignmentRight=2     右對齊
NSTextAlignmentJustified=3 左右兩邊都對齊 一個段落的最後一行是natural-aligned
NSTextAlignmentNatural=4   顯示腳本的默認對齊方式

知識點3:所有NSMutableAttributedString屬性orm

複製代碼
    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;
相關文章
相關標籤/搜索