iOS的UIButton和UILable
初始化UIButton和UILable對象,然後設定按鈕的點擊事件監聽,改變UILable的值為目前時間;
運行:
代碼如下:
//// ViewController.m// tableviewdemo04//// Created by vrinux on 15/6/4.// Copyright (c) 2015年 vrinux. All rights reserved.//#import "ViewController.h"@interface ViewController ()// 定義按鈕;@property (nonatomic,strong) UIButton *mButton;// 定義Label;@property (nonatomic,strong) UILabel *mLable;@end@implementation ViewController- (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view, typically from a nib.// 初始化按鈕; _mButton = [UIButton buttonWithType:UIButtonTypeCustom];// 繪製按鈕的尺寸; _mButton.frame = CGRectMake(100.0f, 100.0f, 200.0f, 100.0f);// 設定背景顏色; [_mButton setBackgroundColor:[UIColor redColor]];// 設定按鈕文字; [_mButton setTitle:@"點擊我吧" forState:UIControlStateNormal];// 設定按鈕的點擊事件,調用函數 onClick: [_mButton addTarget:self action:@selector(onClick:) forControlEvents:UIControlEventTouchUpInside];// 將按鈕添加到view上面; [self.view addSubview:_mButton];// 初始化UILable; _mLable = [[UILabel alloc] initWithFrame:CGRectMake(100, 350, 200, 100)];// 設定字型大小; _mLable.font = [UIFont boldSystemFontOfSize:18.0f];// 設定字型對齊; _mLable.textAlignment = NSTextAlignmentCenter;// 設定文字顏色; _mLable.textColor = [UIColor whiteColor];// 設定背景顏色; [_mLable setBackgroundColor:[UIColor redColor]];// 將按鈕添加到view上面; [self.view addSubview:_mLable];}- (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; // Dispose of any resources that can be recreated.}// 設定點擊事件調用的方法;- (void)onClick:(id)senser{ _mLable.text = [self getDate];}// 擷取目前時間;- (NSString *)getDate{ NSDate * senddate=[NSDate date]; NSDateFormatter *dateformatter=[[NSDateFormatter alloc] init]; [dateformatter setDateFormat:@"YYYY-MM-dd HH:mm:ss"]; NSString * locationString=[dateformatter stringFromDate:senddate]; return locationString;}@end