美文网首页
2018-10-11

2018-10-11

作者: zwz_mistong | 来源:发表于2018-10-11 16:05 被阅读18次

继承 UIControl

一. 初始化

初始化方法

+ (instancetype)buttonWithType:(UIButtonType)buttonType;
UIButtonType枚举如下:
typedef NS_ENUM(NSInteger, UIButtonType) {
    UIButtonTypeCustom = 0,                         // no button type
    UIButtonTypeSystem NS_ENUM_AVAILABLE_IOS(7_0),  //标注系统按钮
    UIButtonTypeDetailDisclosure, // 感叹号❗️图标
    UIButtonTypeInfoLight, // 感叹号❗️图标
    UIButtonTypeInfoDark, // 感叹号❗️图标
    UIButtonTypeContactAdd,// ➕加号️图标
    
    UIButtonTypePlain API_AVAILABLE(tvos(11.0)) API_UNAVAILABLE(ios, watchos), // standard system button without the blurred background view
    
    UIButtonTypeRoundedRect = UIButtonTypeSystem   // Deprecated, use UIButtonTypeSystem instead
};

初始化

UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];

二. 关于UIButton的UIEdgeInsets属性

我们在实际工作当中设计妹妹经常会设计图文共存的button,如下图


image

imagetitle, 或者左titleimage,这时我们就会用到UIButtonUIEdgeInsets属性

UIButton 共有三个相关属性:

  1. contentEdgeInsets
  2. titleEdgeInsets
  3. imageEdgeInsets

先科普一下UIEdgeInsets

它是结构体,四个参数:top 上边界, left 左边界, bottom 下边界, right 右边界, 默认均为0

typedef struct UIEdgeInsets {
    CGFloat top, left, bottom, right;  // specify amount to inset (positive) for each of the edges. values can be negative to 'outset'
} UIEdgeInsets;

1. contentEdgeInsets

如果给按钮设置contentEdgeInsets属性,就是按钮的内容整体(包含UILabel和UIImageView)进行偏移.

先创建一个一个button, 如下图:

image
 //默认图左字右
UIButton *edgeInsetsBtn = [UIButton buttonWithType:UIButtonTypeCustom];
[edgeInsetsBtn setTitle:@"edgeInsets" forState:UIControlStateNormal];
[edgeInsetsBtn setImage:[UIImage imageNamed:@"icon_globe"] forState:UIControlStateNormal];
edgeInsetsBtn.backgroundColor = [UIColor blueColor];
edgeInsetsBtn.frame = CGRectMake(100, 100, 150, 150);
[self.view addSubview:edgeInsetsBtn];

CGFloat imageWidth = edgeInsetsBtn.imageView.bounds.size.width;
CGFloat titleWidth = edgeInsetsBtn.titleLabel.bounds.size.width;
CGFloat imageHeight = edgeInsetsBtn.imageView.bounds.size.height;
CGFloat titleHeight = edgeInsetsBtn.titleLabel.bounds.size.height;

按钮内容整体向右下分别移动20像素:

[edgeInsetsBtn setContentEdgeInsets:UIEdgeInsetsMake(20, 20, -20, -20)];
image
2. titleEdgeInsets & imageEdgeInsets

image的UIEdgeInsets属性的top,left,bottom都是相对于按钮的,right是相对于title

title的UIEdgeInsets属性的top,bottom,right都是相对按钮的,left是相对于image

title在左,image在右:

image
edgeInsetsBtn.titleEdgeInsets = UIEdgeInsetsMake(0, -imageWidth, 0, imageWidth);
edgeInsetsBtn.imageEdgeInsets = UIEdgeInsetsMake(0, titleWidth, 0, -titleWidth);

上图下字:

image
edgeInsetsBtn.imageEdgeInsets = UIEdgeInsetsMake(-imageHeight/2, titleWidth/2, imageHeight/2, -titleWidth/2);
edgeInsetsBtn.titleEdgeInsets = UIEdgeInsetsMake(titleHeight/2, -imageWidth/2, -titleHeight/2, imageWidth/2);

相关文章

网友评论

      本文标题:2018-10-11

      本文链接:https://www.haomeiwen.com/subject/vfibaftx.html