Button 图片和标题位置居中问题
针对按钮的图片和标题的居中问题,
像微信公众帐号带有二级菜单的按钮,图片和标题合起来居中,这就用到了,button.title 和button.image 以及他们的 edgeInsets
【Button 图片和标题位置居中问题】以下是文本和图片从上到下排列,都水平居中的代码,当然也可以另外使用imageView贴到button上,效果是一样的。
//按钮的中心
CGPoint buttonBoundsCenter = CGPointMake(CGRectGetMidX(firstLevelBtn.bounds), CGRectGetMidY(firstLevelBtn.bounds));
//找出imageView最终的center
CGPoint endImageViewCenter = CGPointMake(buttonBoundsCenter.x, CGRectGetMidY(firstLevelBtn.imageView.bounds));
//取得imageView最初的center
CGPoint startImageViewCenter = firstLevelBtn.imageView.center;
CGFloat imageEdgeInsetsLeft = endImageViewCenter.x - startImageViewCenter.x;
CGFloat imageEdgeInsetsTop= endImageViewCenter.y - startImageViewCenter.y+6.5;
CGFloat imageEdgeInsetsBottom = -imageEdgeInsetsTop;
CGFloat imageEdgeInsetsRight= -imageEdgeInsetsLeft;
firstLevelBtn.imageEdgeInsets = UIEdgeInsetsMake(imageEdgeInsetsTop, imageEdgeInsetsLeft, imageEdgeInsetsBottom, imageEdgeInsetsRight);
// 设置titleEdgeInsets
// 找出titleLabel最终的center
CGPoint endTitleLabelCenter = CGPointMake(buttonBoundsCenter.x, CGRectGetHeight(firstLevelBtn.bounds)-CGRectGetMidY(firstLevelBtn.titleLabel.bounds));
// 取得titleLabel最初的center
CGPoint startTitleLabelCenter = firstLevelBtn.titleLabel.center;
CGFloat titleEdgeInsetsTop = endTitleLabelCenter.y-startTitleLabelCenter.y-11-3.5;
CGFloat titleEdgeInsetsLeft = endTitleLabelCenter.x - startTitleLabelCenter.x;
CGFloat titleEdgeInsetsBottom = -titleEdgeInsetsTop;
CGFloat titleEdgeInsetsRight = -titleEdgeInsetsLeft;
firstLevelBtn.titleEdgeInsets = UIEdgeInsetsMake(titleEdgeInsetsTop, titleEdgeInsetsLeft, titleEdgeInsetsBottom, titleEdgeInsetsRight);
推荐阅读
- 宽容谁
- 一个人的旅行,三亚
- 急于表达——往往欲速则不达
- 第6.2章(设置属性)
- 布丽吉特,人生绝对的赢家
- 家乡的那条小河
- 第三节|第三节 快乐和幸福(12)
- 讲述,美丽聪明的海欧!
- 夜游宫|夜游宫 心语
- 增长黑客的海盗法则