自定义button

来源:互联网 发布:六年级数学辅导软件 编辑:程序博客网 时间:2024/04/29 20:34

自定义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




 





例:
0 0