imageEdgeInsets(top,left,bottom,right) 和 titleEdgeInsets(top,left,bottom,right)的值就是我们想要的最终结果与按钮初始状态比较图片和标题的位置分别在上下左右位移的值:
首先
CGFloat imageViewWidth = CGRectGetWidth(button.imageView.frame);
CGFloat labelWidth = CGRectGetWidth(button.titleLabel.frame);
CGFloat buttonWidth = CGRectGetWidth(button.frame);
默认状态UIButton 的 imageEdgeInsets = UIEdgeInsetsMake(0,0,0,0);
titleEdgeInsets = UIEdgeInsetsMake(0,0,0,0);
如果我们希望按钮最终是这样:
也就是最终我们希望图片上下位置不变top = 0, bottom = 0;向右位移一个label的宽度
同时标题上下位置不变top = 0, bottom = 0;向左位移一个图片的宽度
即
imageEdgeInsets = UIEdgeInsetsMake(0,0 + labelWidth,0,0 - labelWidth);
图片相对初始状态左边距加了labelWidth,右边减labelWidth,
以及
titleEdgeInsets = UIEdgeInsetsMake(0,0 - imageViewWidth,0, 0 + imageViewWidth);
如果希望图片和标题都居中,即相对于初始位置图片右移,标题左移
CGFloat button_centerX =CGRectGetMidX(self.bounds);// bounds哦
CGFloat titleLabel_centerX =CGRectGetMidX(self.titleLabel.frame);
CGFloat imageView_centerX =CGRectGetMidX(self.imageView.frame);
imageEdgeInsets = UIEdgeInsetsMake(0,0 + (button_centerX - imageView_centerX),0,0 - (button_centerX - imageView_centerX));
以及
titleEdgeInsets = UIEdgeInsetsMake(0,0 - (titleLabel_centerX - button_centerX),0, 0 + (titleLabel_centerX - button_centerX));