你好,歡迎來到IOS教程網

 Ios教程網 >> IOS使用技巧 >> IOS技巧綜合 >> 你真的了解UIButton、UILabel 嗎?

你真的了解UIButton、UILabel 嗎?

編輯:IOS技巧綜合
[摘要]本文是對你真的了解UIButton、UILabel 嗎?的講解,對學習IOS蘋果軟件開發有所幫助,與大家分享。

一:首先查看一下關於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//為內部框架預留的
};
typedefNSUIntegerUIControlState;

知識點2:contentHorizontalAlignment;可以設置UIButton文字的對齊方式,contentHorizontalAlignment並不是UIButton的屬性,而是它父類UIControl的一個屬性;

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

知識點3:forControlEvents參數類型

typedefNS_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,//rangeavailableforapplicationuse
UIControlEventSystemReserved     =0xF0000000,//rangereservedforinternalframeworkuse
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的協議;

知識點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-aligned
NSTextAlignmentNatural=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;
  1. 上一頁:
  2. 下一頁:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © Ios教程網 All Rights Reserved