美文网首页- 阿成的iOS
#iOS开发#UIButton文字与图片的布局

#iOS开发#UIButton文字与图片的布局

作者: 缱绻一时 | 来源:发表于2017-04-12 15:08 被阅读55次

    前言

    之前对于那种上面是图片下面是文字的按钮都是通过一个ImageView、一个Label、一个Button实现的。ImageView和Label在同一层。然后Button覆盖在他们上面。实现以下效果。

    WX20170411-145933.png

    其实也一直知道Button有一个属性可以去控制这个布局。但是一直都懒得搞...今天看到了就写篇文章分享一下吧。

    正文

    UIButton中有两个属性分别是imageEdgeInsetstitleEdgeInsets用来控制文本与图片的布局。还有一个contentEdgeInsets用来控制内容的布局。
    我们先来看看默认是什么样的。默认值为UIEdgeInsetsZero

    WX20170412-144322.png
        self.button.titleLabel.backgroundColor = [UIColor blueColor];
        self.button.imageEdgeInsets = UIEdgeInsetsZero;
        self.button.titleEdgeInsets = UIEdgeInsetsZero;
    

    <p> </p> <p> </p> <p> </p> <p> </p> <p> </p>

    我们先来看看如果修改titleEdgeInsets会怎么样。

    1、Right为正数

    WX20170412-144001.png
    整个label往左边挪了一点点。但是已经挤压了。
        self.button.titleLabel.backgroundColor = [UIColor blueColor];
        self.button.titleEdgeInsets = UIEdgeInsetsMake(0, 0, 0, 30);
    

    2、Left为正数

    WX20170412-150709@2x.png
    整个label往右边挪了一点点。同样被挤压。
        self.button.titleLabel.backgroundColor = [UIColor blueColor];
        self.button.titleEdgeInsets = UIEdgeInsetsMake(0, 30, 0, 0);
    

    3、Right为负数

    WX20170412-145040@2x.png
    整个label往左边挪了一点点。没有被挤压。
        self.button.titleLabel.backgroundColor = [UIColor blueColor];
        self.button.titleEdgeInsets = UIEdgeInsetsMake(0, -30, 0, 0);
    

    4、Left为负数

    WX20170412-150248@2x.png
    整个label往右边挪了一点点。没有被挤压。
        self.button.titleLabel.backgroundColor = [UIColor blueColor];
        self.button.titleEdgeInsets = UIEdgeInsetsMake(0, 0, 0, -30);
    

    UIEdgeInsets

    补充知识。看到这里我想大家应该都会有一些疑问。那我们就先来看看这个属性。

        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;
    

    这就是一个结构体。里面包含四个变量。分别是上下左右。代表控件距离四周的距离。我们可以看下图会有更清晰的认识。

    1350207-5ea71c94e013a67f.png

    所以我们在上面那部分的实验中。为正数的值往往都是被被挤压的。为负值都会被拉伸。


    1、文字与图片都居中显示

    好了。我们现在去实现让文字与图片都居中显示。

    WX20170414-145631@2x.png
       self.button.titleLabel.backgroundColor = [UIColor blueColor];
       self.button.imageEdgeInsets = UIEdgeInsetsMake(0, 0, 0, -self.button.titleLabel.intrinsicContentSize.width);
       self.button.titleEdgeInsets = UIEdgeInsetsMake(0, -self.button.imageView.frame.size.width, 0, 0);
    

    大家会看到这里有一个intrinsicContentSize。具体的等下会说。大家可以暂时理解为这是lable的实际大小。这里不能使用size。在iOS8之后titleLabel的size为0。是没什么意义的。如果想先理解intrinsicContentSize可以看看这篇文章
    那么我们现在来思考一下这两个值是为什么。相当于我们就是同时将两个控件都移动到了中间。所以文字与图片都居中显示。

    2、文字与图片都水平居中,图片在上、文字在下

    相关文章

      网友评论

        本文标题:#iOS开发#UIButton文字与图片的布局

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