iOS UIButton上下排列(上图下文)


1.

 

-(void)setButtonContentCenter:(UIButton *) btn

 

{

    

    CGSize imgViewSize,titleSize,btnSize;

    

    UIEdgeInsets imageViewEdge,titleEdge;

    

    CGFloat heightSpace = 10.0f;

    

    

    

    //设置按钮内边距

    

    imgViewSize = btn.imageView.bounds.size;

    

    titleSize = btn.titleLabel.bounds.size;

    

    btnSize = btn.bounds.size;

    

    

    

    imageViewEdge = UIEdgeInsetsMake(heightSpace,0.0, btnSize.height -imgViewSize.height - heightSpace, - titleSize.width);

    

    [btn setImageEdgeInsets:imageViewEdge];

    

    titleEdge = UIEdgeInsetsMake(imgViewSize.height +heightSpace, - imgViewSize.width, 0.0, 0.0);

    

    [btn setTitleEdgeInsets:titleEdge];

    

}

2.

-(void)layoutSubviews
{
    [super layoutSubviews];
    CGFloat midX = self.frame.size.width / 2;
    CGFloat midY = self.frame.size.height/ 2 ;
    self.titleLabel.center = CGPointMake(midX, midY + 15);
    self.imageView.center = CGPointMake(midX, midY - 10);
}

3.

    self.titleLabel.backgroundColor = [UIColor greenColor];
    CGSize imageSize = CGSizeMake(self.imageView.frame.size.width-15*RatioWidth, self.imageView.frame.size.height-15*RatioHeight);
    CGSize titleSize = self.titleLabel.frame.size;
    CGSize textSize = [self.titleLabel.text sizeWithFont:self.titleLabel.font];
    CGSize frameSize = CGSizeMake(ceilf(textSize.width), ceilf(textSize.height));
    if (titleSize.width + 0.5 < frameSize.width) {
        titleSize.width = frameSize.width;
    }
    CGFloat totalHeight = (imageSize.height + titleSize.height + spacing);
    self.imageEdgeInsets = UIEdgeInsetsMake(- (totalHeight - imageSize.height), 0.0, 0.0, - titleSize.width);
    self.titleEdgeInsets = UIEdgeInsetsMake(0, - imageSize.width, - (totalHeight - titleSize.height), 0);

4.

    CGSize imgViewSize,titleSize,btnSize;
    imgViewSize = self.imageView.bounds.size;
    titleSize = self.titleLabel.bounds.size;
    btnSize = self.bounds.size;
    //设置按钮内边距
    CGFloat widthSpace = 10*RatioWidth;
//    CGFloat heightSpace = 5*RatioHeight;
    
    UIEdgeInsets imageViewEdge,titleEdge;
    imageViewEdge = UIEdgeInsetsMake(widthSpace,0.0, btnSize.height -imgViewSize.height, - titleSize.width);
    [self setImageEdgeInsets:imageViewEdge];
    
    titleEdge = UIEdgeInsetsMake(imgViewSize.height, - imgViewSize.width, 0.0, 0.0);
    [self setTitleEdgeInsets:titleEdge];

5.

    CGFloat imageW = self.imageView.frame.size.width;
    CGFloat imageH = self.imageView.frame.size.height;
    CGFloat titleW = self.titleLabel.frame.size.width;
    CGFloat titleH = self.titleLabel.frame.size.height;
    [self setImageEdgeInsets:UIEdgeInsetsMake(-titleH, 0.f, 0.f,-titleW)];
    [self setTitleEdgeInsets:UIEdgeInsetsMake(0, -imageW, -imageH - 10, 0.f)];
 注意:titleLabel 的frame 是在 Imageview 加载出来之后才出现的

参考文章:【IOS实战】UIButton 设置图片文字垂直居中排列

 

posted @ 2017-03-10 18:01  听风gcl  阅读(3190)  评论(0编辑  收藏  举报