The Titleedgeinsets and imageedgeinsets in UIButton can manage the layout of the image and title in the button. If the understanding of it is not deep enough, with pure digital layout management, after continuous debugging, or can try out, but if the picture size or text length, but also to do it again. As a procedural ape, we should not give up any chance of laziness.
- By default, the picture is left, the text is in the right, and the vertical center is displayed, such as:
button.titleEdgeInsets = UIEdgeInsetsZero;button.imageEdgeInsets = UIEdgeInsetsZero;
- When you set the following layout, the pictures and text are centered.
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);
- If you want the picture to be on, the text is below, the horizontal center is displayed, then the following settings are required:
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);
If you think the picture and text are too close, a little bit apart:
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);
- Text left-aligned, picture right-aligned
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);
Layout contains the UIButton of the image and title