UIButton设置图片和文字位置

2017-02-27  本文已影响320人  贤宇

开发中经常会遇到左边是图片右边是文字的情况(或者上面是图下面是文字), 这时最好的选择是用UIButton来写, 简单实用.

知识点:

    // Button 有三个设置内边距的属性,分别是:

    // 1.contentEdgeInsets:会影响按钮内部的所有内容(里面的imageView和titleLabel)
    // button.contentEdgeInsets = UIEdgeInsetsMake(10, 100, 0, 0);

    // 2.titleEdgeInsets:只影响按钮内部的titleLabel
    // button.titleEdgeInsets = UIEdgeInsetsMake(0, 10, 0, 0);

    // 3.imageEdgeInsets:只影响按钮内部的imageView
    // button.imageEdgeInsets = UIEdgeInsetsMake(20, 0, 0, 50);

    // EdgeInsets: 内切, 逆时针(上左下右)

举个例子:

    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];

    button.backgroundColor = [UIColor lightGrayColor];
    button.imageView.backgroundColor = [UIColor orangeColor];
    button.titleLabel.backgroundColor = [UIColor greenColor];

    button.imageView.contentMode = UIViewContentModeScaleAspectFit;

    // 内容居左
    button.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;

    [button setImage:[UIImage imageNamed:@"select_yes.png"] forState:UIControlStateNormal];
    [button setTitle:@"一人饮酒醉" forState:UIControlStateNormal];

    // 文字内边距 设置成距离图片15
    button.titleEdgeInsets = UIEdgeInsetsMake(0, 15, 0, 0);

    button.frame = CGRectMake(10, 500, 200, 40);
    [self.view addSubview:button];

效果图:

效果图.png
如果要自适应宽度需要这样设置:
    // 自适应宽度好处会消除imageView多余的空隙.
    button.titleEdgeInsets = UIEdgeInsetsMake(0, 15, 0, 0);
    // 设置自适应大小
    CGSize autoSize = CGSizeMake(100, 999);
    CGSize size = [button sizeThatFits:autoSize];

    // 宽度需要再加上 15
    button.frame = CGRectMake(10, 500, size.width+15, size.height);

效果图:

效果图2.png

补充
文字和图片在按钮的两边:

CGFloat width = [UIScreen mainScreen].bounds.size.width;
    
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    [button setTitle:@"背景音乐使用原音" forState:UIControlStateNormal];
    [button setImage:[UIImage imageNamed:@"select_no.png"] forState:UIControlStateNormal];
    button.backgroundColor = [UIColor orangeColor];
    button.frame = CGRectMake(0, 550, width, 30);
    button.titleLabel.backgroundColor = [UIColor redColor];
    button.imageView.backgroundColor = [UIColor greenColor];

    button.imageView.contentMode = UIViewContentModeScaleAspectFit;
    
    button.titleEdgeInsets = UIEdgeInsetsMake(0, -width+button.titleLabel.frame.size.width-button.imageView.frame.size.width, 0, 0);
    button.imageEdgeInsets = UIEdgeInsetsMake(0, 0, 0, -width+button.imageView.frame.size.width-button.titleLabel.frame.size.width);
    
    [self.view addSubview:button];

效果图

效果图.png
上一篇下一篇

猜你喜欢

热点阅读