1. 程式人生 > >IOS控制元件-UIButton的使用

IOS控制元件-UIButton的使用

//UIButton的使用
    func test1() {
        //建立一個深色背景的提示按鈕
        let button1=UIButton(type: UIButtonType.infoDark)
        //設定按鈕位置大小
        button1.frame=CGRect(x: 130, y: 80, width: 40, height: 40);
        
        
        //建立一個圓角的按鈕
        let button2=UIButton(type: UIButtonType.roundedRect);
        //設定按鈕位置大小
        button2.frame=CGRect(x: 80, y: 180, width: 150, height: 40);
        //設定背景和前景色
        button2.backgroundColor=UIColor.purple
        button2.tintColor=UIColor.yellow;
        button2.setTitle("button2", for: UIControlState());
        button2.addTarget(self, action: #selector(ViewController.button2OnClick(_ :)), for: UIControlEvents.touchUpInside)
        
        
        //建立一個圓角按鈕
        let button3=UIButton(type: UIButtonType.roundedRect);
        //設定背景色 前景色
        button3.backgroundColor=UIColor.brown;
        button3.tintColor=UIColor.white;
        //設定標題
        button3.setTitle("button3", for: UIControlState());
        button3.frame=CGRect(x: 80, y: 280, width: 150, height: 40)
        //設定邊框
        button3.layer.masksToBounds=true;
        //設定按鈕層圓角半徑為10
        button3.layer.cornerRadius=10
        //設定邊框寬度為4
        button3.layer.borderWidth=4
        //設定邊框顏色
        button3.layer.backgroundColor=UIColor.lightGray.cgColor;
        
        self.view.addSubview(button1);
        self.view.addSubview(button2);
        self.view.addSubview(button3);
        

        //建立一個圓角按鈕
        let imgButton = UIButton(type: UIButtonType.roundedRect);
        //設定大小
        imgButton.frame=CGRect(x: 31, y: 530, width: 257, height: 60);
        //設定圖片背景
        imgButton.setBackgroundImage(UIImage(named: "Sample"), for: UIControlState())
        //設定標題
        imgButton.setTitle("imgButton", for: UIControlState())
        //字型
        imgButton.titleLabel?.font=UIFont(name: "Arial", size: 24)
        //顏色
        imgButton.setTitleColor(UIColor.red, for: UIControlState());
        imgButton.addTarget(self, action: #selector(ViewController.button2OnClick(_:)), for: UIControlEvents.touchUpInside);
        self.view.addSubview(imgButton);
    }
    
    @objc func button2OnClick(_ sender:UIButton){
        let dialog=UIAlertController(title: "title", message: "content", preferredStyle: UIAlertControllerStyle.alert)
        let dialogAction    = UIAlertAction(title: "ok", style: UIAlertActionStyle.default, handler: nil);
        dialog.addAction(dialogAction)
        self.present(dialog,animated: true,completion: nil);
        
    }