美文网首页
iOS 封装UIButton,随意调整图片和文字的排版布局

iOS 封装UIButton,随意调整图片和文字的排版布局

作者: 90de46ea2b08 | 来源:发表于2017-05-03 09:18 被阅读198次

模拟一个简单的需求:自定义底部tabbar的按钮,image在上,title在下,并且两者都剧中。

首先创建一个继承自UIButton的类TabbarButton,然后类中的代码如下:

  • TabbarButton.h
//
//  TabbarButton.h
//  anbang_ios
//
//  Created by chenqianfeng on 16/8/26.
//  Copyright © 2016年 ch. All rights reserved.
//

#import <UIKit/UIKit.h>

@interface TabbarButton : UIButton

@end
  • TabbarButton.m
//
//  TabbarButton.m
//  anbang_ios
//
//  Created by chenqianfeng on 16/8/26.
//  Copyright © 2016年 ch. All rights reserved.
//

#import "TabbarButton.h"

@implementation TabbarButton
//图片在上,文字在下(通过改变return的CGRect可以实现不同的布局排版,满足不同的需求)
- (CGRect)imageRectForContentRect:(CGRect)contentRect
{
    float width = contentRect.size.width;
    float height = contentRect.size.height;
    CGRect rect = CGRectMake((width - 51/2)/2, 5, 51/2, 56/2);//2x图片的尺寸 : 51x56
    return rect;
}
- (CGRect)titleRectForContentRect:(CGRect)contentRect
{
    float width = contentRect.size.width;
    float height = contentRect.size.height;
    CGRect rect = CGRectMake(0, 56/2+5+2, width, 13);//文字与图片中间间隔2
    return rect;
}

@end

相关文章

网友评论

      本文标题:iOS 封装UIButton,随意调整图片和文字的排版布局

      本文链接:https://www.haomeiwen.com/subject/rahktxtx.html