範例是在書上看到的,不過程式碼我有改過,因為Swift 3 出來了,而市面書上的範例程式碼... 你懂的
這篇主要是講後端生成程式碼 以Button為例
yourButtonName.addTarget(self, action:#selector(functionName(sender:)), for: .touchUpInside) fun functionName(sender:UIButton) { //.... }
action 這邊 如果沒有回傳值 (sender:) 就不用加了
View 的截圖 自訂12個按鈕
Controller全部程式碼
class ViewController: UIViewController { @IBOutlet weak var labelTel: UITextField! @IBOutlet weak var labelMsg: UILabel! override func viewDidLoad() { super.viewDidLoad() for i in 0...11 { let x:Int = 100 + (i % 4) * 60 let y:Int = 140 + (i / 4) * 60 let buttonNumber:UIButton = UIButton(type: UIButtonType.system) as UIButton //按鈕位置 大小 buttonNumber.frame = CGRect(x: x,y: y,width: 40, height: 35) //文字顏色 buttonNumber.setTitleColor(UIColor.white, for: UIControlState.normal) //按鈕背景 buttonNumber.backgroundColor = UIColor.black //字型大小 buttonNumber.titleLabel?.font = UIFont(name: "System", size: 22.0) if i == 10 { buttonNumber.setTitle("X", for: UIControlState.normal) //加入事件 #selector(funcName(sender:)) 函數是有參數的 buttonNumber.addTarget(self, action:#selector(clearClick(sender:)), for: .touchUpInside) } else if i == 11 { buttonNumber.setTitle("OK", for: UIControlState.normal) buttonNumber.addTarget(self, action:#selector(sureClick(sender:)), for: UIControlEvents.touchUpInside) }else { buttonNumber.setTitle("\(i)", for: UIControlState.normal) buttonNumber.addTarget(self, action:#selector(numberClick(sender:)), for: UIControlEvents.touchUpInside) } //加入按鈕 view.addSubview(buttonNumber) } } func sureClick(sender:UIButton) { if labelTel.text?.lengthOfBytes(using: String.Encoding.utf8) == 10 { labelMsg.text = "Call " + labelTel.text! } else if labelTel.text == "" { labelMsg.text = "Please enter your phone number." } else if (labelTel.text?.lengthOfBytes(using: String.Encoding.utf8))! > 10{ labelMsg.text = "Error" } } func clearClick(sender:UIButton){ labelTel.text = "" labelMsg.text = "" } func numberClick(sender:UIButton) { labelTel.text = labelTel.text! + sender.currentTitle! } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
沒有留言:
張貼留言