Button 图片和标题位置居中问题

针对按钮的图片和标题的居中问题,


像微信公众帐号带有二级菜单的按钮,图片和标题合起来居中,这就用到了,button.title 和button.image 以及他们的 edgeInsets


以下是文本和图片从上到下排列,都水平居中的代码,当然也可以另外使用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);


你可能感兴趣的:(ios)