美文网首页
iOS UIButton中图片和文字位置

iOS UIButton中图片和文字位置

作者: 开心的小娇 | 来源:发表于2019-04-24 16:06 被阅读0次

    如何布局包含ImageTitleUIButton

    UIButton中的titleEdgeInsetsimageEdgeInsets可以管理buttonimagetitle的布局。 

    1.默认情况下,是图片在左,文字在右,垂直居中显示,如下图:

    button.titleEdgeInsets = UIEdgeInsetsZero;

    button.imageEdgeInsets = UIEdgeInsetsZero;

    1

    2.设置如下布局后,图片和文字都居中显示。

    button.titleEdgeInsets = UIEdgeInsetsMake(0,-button.imageView.frame.size.width,0,0);

    // button.imageEdgeInsets = UIEdgeInsetsMake(0,0,0,-button.titleLabel.frame.size.width);

    // 由于iOS8中titleLabel的size为0,用上面这样设置有问题,修改一下即可

    button.imageEdgeInsets = UIEdgeInsetsMake(0,0,0,-button.titleLabel.intrinsicContentSize.width);

    2

    3.如果想图片在上,文字在下,水平居中显示,则按下面设置即可:

    button.titleEdgeInsets = UIEdgeInsetsMake(0,-button.imageView.frame.size.width,-button.imageView.frame.size.height,0);

    // button.imageEdgeInsets = UIEdgeInsetsMake(-button.titleLabel.frame.size.height,0,0,-button.titleLabel.frame.size.width);

    // 由于iOS8中titleLabel的size为0,用上面这样设置有问题,修改一下即可

    button.imageEdgeInsets = UIEdgeInsetsMake(-button.titleLabel.intrinsicContentSize.height,0,0,-button.titleLabel.intrinsicContentSize.width);

    3

    4.如果觉得图片和文字离的太近了,稍微分开一点:

    CGFloat offset = 40.0f;

    button.titleEdgeInsets = UIEdgeInsetsMake(0,-button.imageView.frame.size.width,-button.imageView.frame.size.height-offset/2,0);

    // button.imageEdgeInsets = UIEdgeInsetsMake(-button.titleLabel.frame.size.height-offset/2,0,0,-button.titleLabel.frame.size.width);

    // 由于iOS8中titleLabel的size为0,用上面这样设置有问题,修改一下即可

    button.imageEdgeInsets = UIEdgeInsetsMake(-button.titleLabel.intrinsicContentSize.height-offset/2,0,0,-button.titleLabel.intrinsicContentSize.width);

    4

    5.文字左对齐,图片右对齐

    button.titleEdgeInsets = UIEdgeInsetsMake(0,-button.imageView.frame.size.width - button.frame.size.width + button.titleLabel.intrinsicContentSize.width,0,0);

        button.imageEdgeInsets = UIEdgeInsetsMake(0,0,0,-button.titleLabel.frame.size.width - button.frame.size.width + button.imageView.frame.size.width);

    5

    相关文章

      网友评论

          本文标题:iOS UIButton中图片和文字位置

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