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

2017-05-03  本文已影响198人  90de46ea2b08

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

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

//
//  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
//  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
上一篇 下一篇

猜你喜欢

热点阅读