xcode5中使用代码构造界面UIButton

删掉原来自用的ViewCotroller,新建一个TestViewController

xcode5中使用代码构造界面UIButton_第1张图片



在对应的AppDelegate中didFinishLaunchingWithOptions函数下,加入创建TestViewController视图的代码:

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    self.window = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];
    // Override point for customization after application launch.
    self.window.backgroundColor = [UIColor whiteColor];
    
    [self.window makeKeyAndVisible];
    
    TestViewController *testController = [[TestViewController alloc] init];
    self.window.rootViewController = testController;
    [testController release];

    return YES;
}


这时候View被创建出来了,要想在View上面加入Button,需要在viewDidLoad函数中加入如下创建Button的代码:

- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view.
    
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    btn.frame = CGRectMake(20, 20, 280, 40);
    btn.backgroundColor = [UIColor clearColor];
    [btn setTitle:@"点击" forState:UIControlStateNormal];
    
    [btn addTarget:self
                action:@selector(testOut:)
      forControlEvents:UIControlEventTouchUpInside
     ];
    
    [self.view addSubview:btn];
}



action对应的是这个按钮需要处理的时候(就像这里的testOut函数),forControlEvents后面跟的是我们感兴趣的事件,也就是我们打算和这个函数绑定起来的消息。

testOut函数:

声明(.h中):

- (IBAction)testOut:(UIButton *)sender;


定义(.m中):

- (IBAction)testOut:(UIButton *)sender
{
    NSLog(@"testOut Event");
}



这样写了之后,就可以看到下面的效果:




同样的,这只是简单的代码,如果想要为这个Button的样式做一些调整,还有这样的属性设置:

[btn setImage:[UIImage imageNamed:@"btn.png"] forState:UIControlStateNormal];

等等……


你可能感兴趣的:(xcode5中使用代码构造界面UIButton)