初始化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