要一個一個拉很累,這篇我們就用程式碼來產生這些按鈕
效果如下
程式碼如下 :
// // ViewController.swift // myphone2 // // Created by boywhy chen on 2016/12/16. // Copyright © 2016年 boywhy chen. All rights reserved. // import UIKit class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. //用迴圈建立12個按鈕 for var i=0;i<12;i++ { //按鋌水平位置 var X:Int = 47+(i%3) * 60 //按鈕重直位置 var Y:Int=95+(i/3) * 50 //new 一個UIButton let buttonNumber:UIButton = UIButton() //指定UIButton位置,大小 buttonNumber.frame = CGRect(x: X , y:Y , width: 41 , height:35) //設定UIButton文字的顏色為白色 buttonNumber.setTitleColor(UIColor.whiteColor(), forState: UIControlState.Normal) //設定UIButton的背景色為黑色 buttonNumber.backgroundColor = UIColor.blackColor() //使用系統字型,大小為22 buttonNumber.titleLabel?.font=UIFont(name: "System", size: 22.0) //顯示按鈕的字 if (i == 9) { buttonNumber.setTitle("DEL", forState: UIControlState.Normal) } else if (i == 11) { buttonNumber.setTitle("CLS", forState: UIControlState.Normal) } else { //輸出0~9 buttonNumber.setTitle("\(i%10)", forState: UIControlState.Normal) } //把View加人View Control view.addSubview(buttonNumber) } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
心得:
我一開始看書上照打的,在新增按鈕的地方上出現問題 , 編譯會失敗
var buttonNumber:UIButton = UIButton.buttonWithType(UIButtonType.System) as UIButton
Swift 2之後改用這樣
let buttonNumber:UIButton = UIButton()
Swfit還是在進化丫~
參考資料:
沒有留言:
張貼留言