iOS界面設計之UIButton使用

本文着重介紹使用代碼手寫UIButton。

要想顯示UIButton必須先分配空間並初始化,然後設置一系列屬性,最後將其裝入容器(UIButton作爲subview依附於別的view)。這些代碼可以寫在Controller的ViewDidLoad方法裏。

-(void) viewDidLoad
{
    //調用基類的viewDidLoad
    [super viewDidLoad];

    //創建並初始化UIButton
    UIButton *button = [UIButton new]; //或者使用[[UIButton alloc] init];
    
    //設置UIButton的顯示內容 
    //常規狀態下顯示
    [button setTitle: @"常規模式" forState: UIControlStateNormal];
    //高亮狀態下顯示
    [button setTitle: @"高亮模式" forState: UIControlStateHighlighted];

    //設置文字顏色
    //常規狀態下顯示
    [button setTitleColor: [UIColor greenColor] forState: UIControlStateNormal];
    //高亮狀態下顯示
    [button setTitleColor: [UIColor redColor] forState: UIControlStateHighlighted];

    //設置frme(位置和大小)
    button.frame = CGMake(50, 50, 200, 100); //四個參數依次是xy座標、長寬

    //爲button註冊事件
    [button addTarget: self action:@selector(fun) forControlEvents: UIControlEventTouchUpInside]; //target指定controller action指定處理方法 forControlEvents指定觸發事件

    //把button放到容器中 沒有這步操作button是無法顯示的
    [self.view addView: button];
}

UIButton中的文字默認居中。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章