IOS UIButton 简单应用

2011-06-12

objective-c 开发过程是经常用到 UIButton 控件。 简单介绍写 UIButton 的使用 (也包括了一个简单的 delegate 的实现)。

首先, View的实现


视图头文件 View.h

#import 
// delegate声明
@protocol btnAction 
-(void)getDetail;
@end

@interface SAView : UIView {
    id delegate;
}

@property (nonatomic, assign) id delegate;

-(void) getDetail:(id)sender;

@end

实现文件 View.m

#import "SAView.h"


@implementation SAView

@synthesize delegate;

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code
        [self setBackgroundColor:[UIColor grayColor]];
        UIButton * btn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
        btn.frame = CGRectMake(20, 20, 200, 40);
        [btn setTitle:@"Cilck Me!" forState:UIControlStateNormal];
        [btn addTarget:self action:@selector(getDetail:) forControlEvents:UIControlEventTouchUpInside];
        
        [self addSubview:btn];

    }
    return self;
}
-(void)getDetail:(id)sender
{
    [delegate getDetail];
}

- (void)dealloc
{
    [super dealloc];
}
@end

然后,Controller 的实现


Controller.h

#import 
#import "SAView.h"
@interface rootController : UIViewController {
    
}
@end

Controller.m

#import "rootController.h"


@implementation rootController


- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)dealloc
{
    [super dealloc];
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle


// Implement loadView to create a view hierarchy programmatically, without using a nib.
- (void)loadView
{
    SAView * main = [[SAView alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    main.delegate = self;
    
    self.view = main;
    [main release];
    
}


/*
// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad
{
    [super viewDidLoad];
}
*/

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

-(void)getDetail
{
    NSLog(@"OK");
}

@end

以上就是简单的 UIButton 和delegate的应用