iOS开发UI篇--UIButton

一、简介

  •  UIButton按钮是IOS开发中最常用的控件,作为IOS基础学习教程知识 ,初学者需要了解其基本定义和常用设置,以便在开发中熟练运用。
  •  UIButton类继承自UIControl类,可以通过点击实现程序与用户之间的交互。

   

 二、关于UIButton的苹果官方API的解释 

  一、一些基本属性   

NS_ASSUME_NONNULL_BEGIN

@class UIImage, UIFont, UIColor, UIImageView, UILabel;

按钮的枚举

typedef NS_ENUM(NSInteger, UIButtonType) {

    UIButtonTypeCustom = 0,                         // no button type

    UIButtonTypeSystem NS_ENUM_AVAILABLE_IOS(7_0),  // standard system button

    UIButtonTypeDetailDisclosure,

    UIButtonTypeInfoLight,

    UIButtonTypeInfoDark,

    UIButtonTypeContactAdd,

    

    UIButtonTypeRoundedRect = UIButtonTypeSystem,   // Deprecated, use UIButtonTypeSystem instead    这个方法已经废弃,用 UIButtonTypeSystem替代

};

NS_CLASS_AVAILABLE_IOS(2_0) @interface UIButton : UIControl <NSCoding>

+ (instancetype)buttonWithType:(UIButtonType)buttonType; 单例创建按钮

@property(nonatomic)          UIEdgeInsets contentEdgeInsets UI_APPEARANCE_SELECTOR; // default is UIEdgeInsetsZero 整个内容的内边距

@property(nonatomic)          UIEdgeInsets titleEdgeInsets;                // default is UIEdgeInsetsZero   标题的内边距

@property(nonatomic)          BOOL         reversesTitleShadowWhenHighlighted; // default is NO. if YES, shadow reverses to shift between engrave and emboss appearance

@property(nonatomic)          UIEdgeInsets imageEdgeInsets;                // default is UIEdgeInsetsZero 图片的内边距

@property(nonatomic)          BOOL         adjustsImageWhenHighlighted;    // default is YES. if YES, image is drawn darker when highlighted(pressed) 高亮状态点击图片变暗

@property(nonatomic)          BOOL         adjustsImageWhenDisabled;       // default is YES. if YES, image is drawn lighter when disabled 禁用状态变灰

@property(nonatomic)          BOOL         showsTouchWhenHighlighted __TVOS_PROHIBITED;      // default is NO. if YES, show a simple feedback (currently a glow) while highlighted

@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.

@property(nonatomic,readonly) UIButtonType buttonType;

二、给不同状态设置图片,标题,标题颜色,背景图片,背景阴影颜色

// you can set the image, title color, title shadow color, and background image to use for each state. you can specify data

// for a combined state by using the flags added together. in general, you should specify a value for the normal state to be used

// by other states which don't have a custom value set 

  • 你可以同时给不同的状态指定值。一般来说,在其他状态没有一个定制的值时,你应该为正常状态指定一个值

- (void)setTitle:(nullable NSString *)title forState:(UIControlState)state;                     // default is nil. title is assumed to be single line  设置标题

- (void)setTitleColor:(nullable UIColor *)color forState:(UIControlState)state UI_APPEARANCE_SELECTOR; // default if nil. use opaque white 设置标题颜色

- (void)setTitleShadowColor:(nullable UIColor *)color forState:(UIControlState)state UI_APPEARANCE_SELECTOR; // default is nil. use 50% black  设置标题阴影颜色

- (void)setImage:(nullable UIImage *)image forState:(UIControlState)state;                      // default is nil. should be same size if different for different states 设置图片

- (void)setBackgroundImage:(nullable UIImage *)image forState:(UIControlState)state UI_APPEARANCE_SELECTOR; // default is nil 设置背景图片

- (void)setAttributedTitle:(nullable NSAttributedString *)title forState:(UIControlState)state NS_AVAILABLE_IOS(6_0); // default is nil. title is assumed to be single line  设置富文本标题

// these getters only take a single state value 以下这些getters返回特定状态的值,返回值与上面的方法相对应

- (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);

三、其他状态缺少设置是可以使用正常状态的值,简称缺省使用normal的值

// these are the values that will be used for the current state. you can also use these for overrides. a heuristic will be used to

// determine what image to choose based on the explict states set. For example, the 'normal' state value will be used for all states

// that don't have their own image defined.

@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

四、return title and image views.

// return title and image views. will always create them if necessary. always returns nil for system buttons

@property(nullable, nonatomic,readonly,strong) UILabel     *titleLabel NS_AVAILABLE_IOS(3_0);

@property(nullable, nonatomic,readonly,strong) UIImageView *imageView  NS_AVAILABLE_IOS(3_0);

五、返回大小,范围

// these return the rectangle for the background (assumes bounds), the content (image + title) and for the image and title separately. the content rect is calculated based

// on the title and image size and padding and then adjusted based on the control content alignment. there are no draw methods since the contents

// are rendered in separate subviews (UIImageView, UILabel)

- (CGRect)backgroundRectForBounds:(CGRect)bounds;

- (CGRect)contentRectForBounds:(CGRect)bounds;

- (CGRect)titleRectForContentRect:(CGRect)contentRect;

- (CGRect)imageRectForContentRect:(CGRect)contentRect;

@end

六、已经废弃不用的

@interface UIButton(UIButtonDeprecated)

@property(nonatomic,strong) UIFont         *font              NS_DEPRECATED_IOS(2_0, 3_0) __TVOS_PROHIBITED;

@property(nonatomic)        NSLineBreakMode lineBreakMode     NS_DEPRECATED_IOS(2_0, 3_0) __TVOS_PROHIBITED;

@property(nonatomic)        CGSize          titleShadowOffset NS_DEPRECATED_IOS(2_0, 3_0) __TVOS_PROHIBITED;

@end

NS_ASSUME_NONNULL_END

  

三、代码例子

- (void)viewDidLoad {

    [super viewDidLoad];

    // Do any additional setup after loading the view, typically from a nib.

    

    self.view.backgroundColor = [UIColor whiteColor];

    

    

      [self createButton];

}

- (void)createButton{

    

    

//    1.UIButton的实例化

    

    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];

    

/*      能够定义的button类型有以下7种,

    

      typedef enum {

        

          UIButtonTypeCustom = 0, 自定义风格 无样式, 最常用

        

        

        

        UIButtonTypeRoundedRect = UIButtonTypeSystem   //圆角矩形

        

        

        

        UIButtonTypeSystem          // 可以正常的显示内容, 但是, 不方便自定义

        

          UIButtonTypeDetailDisclosure, 蓝色小箭头按钮,主要做详细说明用

        

          UIButtonTypeInfoLight, 亮色感叹号

        

          UIButtonTypeInfoDark, 暗色感叹号

        

          UIButtonTypeContactAdd, 十字加号按钮

        

          } UIButtonType;

    

*/

    

//     2.设置UIButton的大小

    

    button.frame = CGRectMake(50, 100, 200, 100);

     

//    3. 设置边框

    

    button.layer.borderColor = [UIColor grayColor].CGColor;

    

    button.layer.borderWidth = 0.5f;

     

//    4. 绘制圆角

    

    button.layer.cornerRadius = 5.f;

    

    button.layer.masksToBounds = YES;

     

//    5. 背景颜色

    

    button.backgroundColor = [UIColor redColor];

//    6.设置button标题和标题颜色

    

    [button setTitle:@"点我啊!" forState:UIControlStateNormal];

     

    [button setTitleColor:[UIColor yellowColor] forState:UIControlStateNormal];

    

/*      forState: 这个参数的作用是定义按钮的文字或图片在何种状态下才会显现

    

        

          UIControlStateNormal = 0, 常规状态显现// 正常状态, 不对button做任何的操作

         

          UIControlStateHighlighted = 1 << 0, 高亮状态显现 点下去不是高亮, 而是正常状态(理解)

          UIControlStateDisabled = 1 << 1, 禁用的状态才会显现

        

          UIControlStateSelected = 1 << 2, 选中状态

        

          UIControlStateApplication = 0x00FF0000, 当应用程序标志时

        

          UIControlStateReserved = 0xFF000000 为内部框架预留,可以不管

        

          };

    

  */

    

    // 禁用状态需要设置

    

    button.enabled = YES;    //是否禁用

    

    // 设置选中状态

    

    button.selected = NO;// 是否选中

    /*

    @property(nonatomic,getter=isEnabled)BOOL enabled; // default is YES. if NO, ignores touch events and subclasses may draw differently

    

      @property(nonatomic,getter=isSelected)BOOL selected; // default is NO may be used by some subclasses or by application

    

      @property(nonatomic,getter=isHighlighted)BOOL highlighted;

  */

    

    

    // 如果没有设置高亮,禁用... 其他状态的标题, 标题颜色, 背景图片, 标题图片 缺省使用正常状态的

    

     

//    7. 设置标题的字体

    

    button.titleLabel.font = [UIFont boldSystemFontOfSize:30];

     

//    8.设置button填充图片和背景图片

     

    // UIImage 是一个用来加载图片图片类,而UIImageView是在界面上显示图片的一个控件。在UIImageView中显示图片的话应该首先把图片加载到UIImage中,然后通过其他方式使用该UIImage。以下说明了四种常用的加载UIImage的方法:

//imageNamed:使用应用程序束中的一个文件来创建,IOS4以后的版本中可以省略图片扩展名;

//imageWithCGImage:使用Quartz 2D对象创建UIImage,与initWithCGImage等效;

//    imageWithContentsOfFile:根据指定的路径创建UIImage,与initWithContentOfFile等效;

//    imageWithData:使用NSData创建,与initWithData等效;

  

    // 设置button的背景图片

    

    [button setBackgroundImage:[UIImage imageNamed:@"logo"] forState:UIControlStateNormal];

    

    // 设置button的标题图片,标题图片会跟随着标题整体居中

    

    [button setImage:[UIImage imageNamed:@"logo"] forState:UIControlStateNormal];

     

    

    /*9.

     

     * 默认情况下,当按钮高亮的情况下,图像的颜色会被画深一点,如果这下面的这个属性设置为no,

     

     * 那么可以去掉这个功能

     

     */

    

    button.adjustsImageWhenHighlighted = NO;

     

    /*跟上面的情况一样,默认情况下,当按钮禁用的时候,图像会被画得深一点,设置NO可以取消设置*/

    

    button.adjustsImageWhenDisabled = NO;

     

    

    /* 下面的这个属性设置为yes的状态下,按钮按下会发光*/

    

    button.showsTouchWhenHighlighted = YES;

         

//    10.设置按钮内部图片间距和标题间距

    

    button.contentEdgeInsets = UIEdgeInsetsMake(10, 10, 10, 10);

  // 标题间距

    

    [button setTitleEdgeInsets:UIEdgeInsetsMake(0, 0, 0, 0)

     ];

    

    

//    11.给button注册事件(Target - action 目标动作机制 )

    

    /*

     

     target: 接收消息的对象 (目标)

     

     action: 发送的消息, 如果方法需要参数, 参数类型必须是UIButton

     

     controlEvent: 触发条件

     

     UIControlEventTouchDown        // 点下去(不用松手)

     

     UIControlEventTouchDownRepeat  // 重复点击(需要快速点击触发)

     

     UIControlEventTouchDragInside  // 在内部拖动

     

     UIControlEventTouchDragOutside // 在外部拖动

     

     UIControlEventTouchDragEnter   // 拖动进入button

     

     UIControlEventTouchDragExit    // 拖动离开button

          

     // 这个条件, 符合用户习惯, 最常使用

     

     UIControlEventTouchUpInside    // 点击button, 在内部松开

           

     UIControlEventTouchUpOutside   // 点击button, 在外部松开

     

     UIControlEventTouchCancel      // 点击取消, 无法模拟

     

     */

     

    [button addTarget:self action:@selector(buttonAction:) forControlEvents:UIControlEventTouchUpInside];

     

    //    self performSelector:SE withObject:self

   

    [self.view addSubview:button];

- (void)buttonAction:(UIButton *)button {

    

    // 打印button的标题

     NSString *title = [button titleForState:UIControlStateNormal];

    

    NSLog(@"%@", title);

    

}

   

博主的话

以前看过很多别人的博客,学到不少东西。现在准备自己也开始写写博客,希望能够帮到一些人。 

 

原文地址:https://www.cnblogs.com/dreamDeveloper/p/5947710.html