UIButton的相关技巧

自定义UIButton

UIButton能够设置一个背景图片,图标,以及文字字体

若是同时设置图标和文字,默认文字在右边,图片在左边。
spa

若是须要自定义一个下图的效果,就须要自定义一个UIButton
code


在这个方法中进行初始化
orm

- (id)initWithFrame:(CGRect)frame;
图片



改写- (CGRect)imageRectForContentRect:(CGRect)contentRect;这个方法来设置图标的位置it

改写- (CGRect)titleRectForContentRect:(CGRect)contentRect;这个方法来设置文字label的位置io


#import "HMTitleButton.h"

@implementation HMTitleButton

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        // 内部图标居中
        self.imageView.contentMode = UIViewContentModeCenter;
        // 文字对齐
        self.titleLabel.textAlignment = NSTextAlignmentRight;
        // 文字颜色
        [self setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        // 字体
        self.titleLabel.font = HMNavigationTitleFont;
        // 高亮的时候不须要调整内部的图片为灰色
        self.adjustsImageWhenHighlighted = NO;
    }
    return self;
}

/**
 *  设置内部图标的frame
 */
- (CGRect)imageRectForContentRect:(CGRect)contentRect
{
    CGFloat imageY = 0;
    CGFloat imageW = self.height;
    CGFloat imageH = imageW;
    CGFloat imageX = self.width - imageW;
    return CGRectMake(imageX, imageY, imageW, imageH);
}

/**
 *  设置内部文字的frame
 */
- (CGRect)titleRectForContentRect:(CGRect)contentRect
{
    CGFloat titleY = 0;
    CGFloat titleX = 0;
    CGFloat titleH = self.height;
    CGFloat titleW = self.width - self.height;
    return CGRectMake(titleX, titleY, titleW, titleH);
}

@end



我之前竟然很傻很天真的去初始化3个控件,底部UIButton,上面放UIImageView和UILabel真是够了。。。class

相关文章
相关标签/搜索