UIAlertController 提示框


宣告資料

var button = UIButton()
let WIDTH = UIScreen.main.bounds.size.width

viewDidLoad

view.backgroundColor = .lightGray
    button.frame.size = CGSize(width: 100, 
                               height: 50)
    button.center = CGPoint(x: WIDTH / 2, 
                            y: 75)
    button.setTitle("test", 
                    for: .normal)
    button.setTitleColor(.white, 
                         for: .normal)
    button.backgroundColor = .black
    button.contentHorizontalAlignment = .center
    button.layer.cornerRadius = 10
    button.addTarget(self, 
                     action: #selector(buttonpressed), 
                     for: .touchDown)
view.addSubview(button)

建立跳出提示框動作

func buttonpressed(sender: UIButton) {
    // 建立提示框
    let alert = UIAlertController(title: "標題測試",
                                  message: "文字內容測試",
                                  preferredStyle: .alert)
    /*
    UIAlertControllerStyle
     .actionSheet     底部滑出
     .alert           螢幕中跳出
     */
        // 文字輸入框, 無法放置底部
        alert.addTextField(configurationHandler: {(text: UITextField!) -> Void in
            text.placeholder = "文字輸入測試"
            text.textAlignment = .center
        })
        // 無動作
        let cancel = UIAlertAction(title: "清除",
                                   style: .cancel,
                                   handler: nil)
        alert.addAction(cancel)
        /*
         UIAlertActionStyle
         .cancel          位置固定左, 下
         .default         預設
         .destructive     紅色警示
         */
        // 加入動作, 更換按鈕title
        let done = UIAlertAction(title: "更換按鈕文字",
                                 style: .default,
                                 handler: {(action: UIAlertAction!) -> Void in
            self.button.setTitle(alert.textFields?.first?.text,
                                 for: .normal)
        })
        alert.addAction(done)
    present(alert, 
            animated: true, 
            completion: nil)
}

results matching ""

    No results matching ""