按钮内部title和image调整

#import "QHTitleButton.h"
#import "UIView+Extension.h"

@implementation QHTitleButton

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
//        self.imageView.contentMode = UIViewContentModeCenter;
        [self setTitleColor:[UIColor blackColor] forState:UIControlStateNormal ];
        self.titleLabel.font = [UIFont boldSystemFontOfSize:17];
        [self setImage:[UIImage imageNamed:@"navigationbar_arrow_down"] forState:UIControlStateNormal];
        [self setImage:[UIImage imageNamed:@"navigationbar_arrow_up"] forState:UIControlStateSelected];
    }
    
    return self;
}
/**
 *  设置按钮内部的imageView的frame
 *
 *  @param contentRect 按钮的bounds
 *
 */
//- (CGRect)imageRectForContentRect:(CGRect)contentRect
//{
//    CGFloat x = 80;
//    CGFloat y = 0;
//    CGFloat width = 13;
//    CGFloat height = contentRect.size.height;
//    
//    return CGRectMake(x, y, width, height);
//}
///**
// *  设置按钮内部的titleLabel的frame
// *
// *  @param contentRect 按钮的bounds
// *
// */
//- (CGRect)titleRectForContentRect:(CGRect)contentRect
//{
//    CGFloat x = 0;
//    CGFloat y = 0;
//    CGFloat width = 80;
//    CGFloat height = contentRect.size.height;
//    
//    return CGRectMake(x, y, width, height);
//}


/**
 *  系统计算完和设置完按钮的尺寸后在修改一下尺寸
 重写setFrame 方法拦截设置按钮尺寸
 */
- (void)setFrame:(CGRect)frame
{
    frame.size.width += 10;
    [super setFrame:frame];
}

- (void)layoutSubviews
{
    [super layoutSubviews];
    //如果仅仅是调整按钮内部 titleLabel imageView 的位置 那么我们在layoutSubView中单独设置位置即可
    //1.计算lable 的frame
    self.titleLabel.x = 0;
    self.imageView.x = CGRectGetMaxX(self.titleLabel.frame) + 5;
//    NSMutableDictionary *attrs = [NSMutableDictionary dictionary];
//    attrs[NSFontAttributeName] = self.titleLabel.font;
//    CGFloat titleW = [self.currentTitle sizeWithAttributes:attrs].width;
    
    //2.计算imageView frame
}

- (void)setTitle:(NSString *)title forState:(UIControlState)state
{
    [super setTitle:title forState:state];
    [self sizeToFit];
}

- (void)setImage:(UIImage *)image forState:(UIControlState)state
{
    [super setImage:image forState:state];
    [self sizeToFit];
}

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

@end

你可能感兴趣的:(ios,方法,ios开发)