//根據(jù)效果圖1我們先來(lái)獲得imageView的center
CGPoint imageViewCenterNow = button.imageView.center;
//根據(jù)效果圖1我們先來(lái)獲得titleLabel的center
CGPoint titleLabelCenterNow = button.titleLabel.center;
//獲得Button的Center
CGPoint buttonBoundsCenter = CGPointMake(CGRectGetMidX(button.bounds), CGRectGetMidY(button.bounds));
//根據(jù)效果圖2我們先來(lái)獲得imageView最終想要得到的center
CGPoint imageViewCenter = CGPointMake(buttonBoundsCenter.x, CGRectGetMidY(button.imageView.bounds));
//根據(jù)效果圖2我們?cè)賮?lái)獲得titleLabel最終想要得到的center
CGPoint titleLabelCenter = CGPointMake(buttonBoundsCenter.x, CGRectGetHeight(button.bounds) - CGRectGetMidY(button.titleLabel.bounds));
//根據(jù)兩個(gè)圖的差異我們來(lái)設(shè)置imageEdgeInsets
//因?yàn)槲覀円獙D上移耍目,所以top一定是負(fù)值膏斤,bottom一定是正值,因?yàn)槲覀円獙D右移邪驮,所以left一定是正值莫辨,right一定是負(fù)值
CGFloat imageEdgeInsetsTop = imageViewCenter.y - imageViewCenterNow.y;
CGFloat imageEdgeInsetsLeft = imageViewCenter.x - imageViewCenterNow.x;
CGFloat imageEdgeInsetsBottom = -imageEdgeInsetsTop;
CGFloat imageEdgeInsetsRight = - imageEdgeInsetsLeft;
UIEdgeInsets imageInsets = UIEdgeInsetsMake(imageEdgeInsetsTop, imageEdgeInsetsLeft, imageEdgeInsetsBottom, imageEdgeInsetsRight);
button.imageEdgeInsets = imageInsets;
//根據(jù)兩個(gè)圖的差異我們來(lái)設(shè)置titleEdgeInsets,跟image同理
CGFloat titleEdgeInsetsTop = titleLabelCenter.y - titleLabelCenterNow.y;
CGFloat titleEdgeInsetsLeft = titleLabelCenter.x - titleLabelCenterNow.x;
CGFloat titleEdgeInsetsBottom = -titleEdgeInsetsTop;
CGFloat titleEdgeInsetsRight = -titleEdgeInsetsLeft;
UIEdgeInsets titleInsets = UIEdgeInsetsMake(titleEdgeInsetsTop, titleEdgeInsetsLeft, titleEdgeInsetsBottom, titleEdgeInsetsRight);
button.titleEdgeInsets = titleInsets;
原創(chuàng)者:http://neusoftios.blog.51cto.com/9977509/1620510