UIButton设置图片和标题上下垂直分布的总结

我们在使用UIButton的时候大多都是 图片 和 文字 水平分布的,当需要垂直分布的时候就需要去设置EdgeInsets:

 

btn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter;//使图片和文字水平居中显示
[btn setTitleEdgeInsets:UIEdgeInsetsMake(btn.imageView.frame.size.height ,-btn.imageView.frame.size.width, 0.0,0.0)];//文字距离上边框的距离增加imageView的高度,距离左边框减少imageView的宽度,距离下边框和右边框距离不变
[btn setImageEdgeInsets:UIEdgeInsetsMake(0.0, 0.0,0.0, -btn.titleLabel.bounds.size.width)];//图片距离右边框距离减少图片的宽度,其它不边

但是当我用上面的方法设置过以后,改变标题文字多少的时候,图片的位置又变了,这种方法的通用性不行

然后通过重写UIButton的-(void)layoutSubviews方法去实现,具体如下:

-(void)layoutSubviews{

    [super layoutSubviews];
    
    CGFloat text_Height = 20.0;
    
    // Center image
    CGPoint center = self.imageView.center;
    center.x = self.frame.size.width/2.0;
    //center.y = self.imageView.frame.size.height/2.0;
    self.imageView.center = center;
    CGRect imgViewFrame = [self imageView].frame;
    imgViewFrame.origin.y = 10.0;
    imgViewFrame.size.height = self.frame.size.height - 25.0 - text_Height;
    imgViewFrame.size.width = self.frame.size.height - 25.0 - text_Height;
    self.imageView.frame = imgViewFrame;
    
    //Center text
    CGRect titleFrame = [self titleLabel].frame;
    titleFrame.origin.x = 0;
    titleFrame.origin.y = self.imageView.frame.origin.y + self.imageView.frame.size.height + 10.0;
    titleFrame.size.width = self.frame.size.width;
    titleFrame.size.height = text_Height;
    self.titleLabel.frame = titleFrame;
    
    self.titleLabel.textAlignment = NSTextAlignmentCenter;
    
}

这种方法可以根据自己的需求去设置图片,文字的边距和大小,效果还是很好的

 

另外如果你还是不满意的话,那就自定义吧,什么样的效果都可以用自定义去实现!

 

posted @ 2017-07-05 17:35  #零下一度&  阅读(389)  评论(0编辑  收藏  举报