自定义button

自定义button:可以通过子类化按钮来定制属于你自己的按钮类——自定义一个类继承自,然后用这个子类创建按钮即可;

在子类化的时候你可以重载下面这些方法,这些方法返回CGRect结构,指明了按钮每一组成部分的边界。
注意:不要直接调用这些方法, 这些方法是你写给系统调用的。


下面是系统提供的方法

/ these return the rectangle for the background (assumes bounds), the content (image + title) and for the image and title separately. the content rect is calculated based
// on the title and image size and padding and then adjusted based on the control content alignment. there are no draw methods since the contents
// are rendered in separate subviews (UIImageView, UILabel)

- (CGRect)backgroundRectForBounds:(CGRect)bounds;
- (CGRect)contentRectForBounds:(CGRect)bounds;
- (CGRect)titleRectForContentRect:(CGRect)contentRect;
- (CGRect)imageRectForContentRect:(CGRect)contentRect;




下面是一个例子: 为按钮imageView和label两部分,分别设置区域空间大小。
//  Created by kevin on 14-2-11.
//  Copyright (c) 2014年 kevin. All rights reserved.
//

#import "KSExButton.h"
#define KSImageScale 0.5

@implementation KSLocationButton

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        
        // 1、顶部图片
        self.imageView.contentMode = UIViewContentModeCenter;
        [self setImage:[UIImage imageNamed:@"kevin"] forState:UIControlStateNormal];
        [self setImage:[UIImage imageNamed:@"kevin1"] forState:UIControlStateSelected];
        
        // 2、设置文字
        self.titleLabel.textAlignment = NSTextAlignmentCenter;
        [self setTitle:@"按钮" forState:UIControlStateNormal];
        [self setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
        [self setTitleColor:[UIColor whiteColor] forState:UIControlStateSelected];
    }
    return self;
}


#pragma mark - 设置按钮内部图片和文字的frame
- (CGRect)imageRectForContentRect:(CGRect)contentRect
{
    CGFloat W = contentRect.size.width;
    CGFloat H = contentRect.size.height *KSImageScale;
    return CGRectMake(0, 0, W, H);
}
- (CGRect)titleRectForContentRect:(CGRect)contentRect
{
    CGFloat W = contentRect.size.width;
    CGFloat H = contentRect.size.height *KSImageScale;
    CGFloat y = contentRect.size.height - H;
    return CGRectMake(0, y, W, H);
}

@end




 





例:
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值