这篇文章将为大家详细讲解有关iOS怎么将UIButton中的图片与文字上下对齐,小编觉得挺实用的,因此分享给大家做个参考,希望大家阅读完这篇文章后可以有所收获。
<强>设置图片和文字强>
如示例代码:
func initView (),→, Void { 时间=var 按钮:UIButton UIButton(框架:CGRectMake (100,, 200,, 100,, 100)) button.setImage(用户界面图像(命名为:“button.png"),, forState:, UIControlState.Normal) button.setTitle(“按钮,,,forState:, UIControlState.Normal) 时间=button.backgroundColor UIColor.blueColor () self.view.addSubview(按钮) }
我们可以通过UIButton的setTitle和setImage方法分别为按钮设置图片和文字信息,但是会发现设置完成以后我们的图片和文字并没有重合排列,也没有上下排列,而是一个左右排列的样子。
func initView (),→, Void { 时间=var 按钮:UIButton UIButton(框架:CGRectMake (100,, 200,, 100,, 100)) button.setImage(用户界面图像(命名为:“button.png"),, forState:, UIControlState.Normal) button.setTitle(“按钮,,,forState:, UIControlState.Normal) 时间=button.backgroundColor UIColor.blueColor () button.titleLabel .frame =, CGRectMake(20,, 0,, 30日,30) 时间=button.imageView ? .frame CGRectMake(0, 0, 20日,20) self.view.addSubview(按钮) }
修改为这样以后,运行程序,会发现对应的视图没有任何变化。
titleEdgeInsets =,(时间+ h3 空间,,安康;w2,, 0, 0) imageEdgeInsets =, (-h2 安康;空间,,w1)
如上述例子若改为:
func initView (),→, Void { 时间=var 按钮:UIButton UIButton(框架:CGRectMake (100,, 200,, 100,, 100)) button.setImage(用户界面图像(命名为:“button.png"),, forState:, UIControlState.Normal) button.setTitle(“按钮,,,forState:, UIControlState.Normal) 时间=button.backgroundColor UIColor.blueColor () 时间=var 图象尺寸:CGSize button.imageView ! .frame.size 时间=var titleSize: CGSize button.titleLabel ! .frame.size button.titleEdgeInsets =, UIEdgeInsets(:, 0,,左:-imageSize.width,,底部:,-imageSize.height 作用;5,右:,0) button.imageEdgeInsets =, UIEdgeInsets (:, -titleSize.height 作用;5,左:,0,,底部:,0,,右:,-titleSize.width) self.view.addSubview(按钮) }
则可实现我们要求的效果: