View和Controller代码组织

本文介绍如何使用Objective-C编程语言创建一个简单的按钮点击事件控制器,包括按钮的初始化、事件连接、文本设置和布局调整。通过实现按钮点击事件,展示了如何在iOS应用中进行基本的交互操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

//
// MyView.h
//

#import <UIKit/UIKit.h>

@interface MyView : UIView {
UIButton
* m_button;
}

/**
* 关联event,delegate
*/
-(void)connection:(id)target;
-(void)setButtonText:(NSString*)text;

@end

//
// MyView.m
//

#import "MyView.h"
@implementation MyView


- (id)initWithFrame:(CGRect)frame
{
self
= [super initWithFrame:frame];
if (self) {
/**
* 组装view
*/
m_button
= [[UIButton buttonWithType:UIButtonTypeRoundedRect] retain];
[m_button setTitle:
@"tap me!" forState:UIControlStateNormal];
[self addSubview:m_button];
}
return self;
}

-(void)connection:(UIController*)target{
[m_button addTarget:target action:@selector(buttonClick:) forControlEvents:UIControlEventTouchUpInside];
}

-(void)setButtonText:(NSString*)text{
[m_button setTitle:text forState:UIControlStateNormal];
}

/**
* 调整布局
*/
-(void)layoutSubviews{
m_button.frame
= CGRectMake(100, 100, 64, 24);
}

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

@end

//
// MyController.h
//

#import <UIKit/UIKit.h>

@class MyView;
@interface MyController : UIViewController {
/**
* 关联view
*/
MyView
* m_myView;

/**
* 模型数据
*/
NSInteger m_tapCount;
}

@end

//
// MyController.m
//

#import "MyController.h"
#include
"MyView.h"

@implementation MyController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self
= [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
/**
* 初始化controller
*/
self
->m_tapCount = 0;
}
return self;
}

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

//-(void)didReceiveMemoryWarning
//{
// [super didReceiveMemoryWarning];
//}

#pragma mark - event

-(void)buttonClick:(id)sender{
[m_myView setButtonText:[NSString stringWithFormat:
@"%d", ++self->m_tapCount]];
}

/**
* 加载自定义view
*/
- (void)loadView
{
m_myView
= [[MyView alloc] initWithFrame:CGRectZero];
self.view
= m_myView;
[m_myView connection:self];
}

//- (void)viewDidLoad
//{
// [super viewDidLoad];
//}
//
//- (void)viewDidUnload
//{
// [super viewDidUnload];
//}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

@end

  

转载于:https://www.cnblogs.com/delonchen/archive/2011/07/23/view-controller.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值