Swift出來已經(jīng)有3年多了泛粹,在最近的一次計(jì)算機(jī)語言排行中溶褪,swift已經(jīng)殺入了前十行列入问。作為一位iOS開發(fā)者食茎,遲遲沒有入手swift確實(shí)說不過去(這里不談工作)蒂破,但我一直相信,學(xué)習(xí)這種事就跟種樹一樣别渔,在兩種時(shí)候最好附迷,一種是十年前惧互,另一種則是現(xiàn)在。所以挟秤,在這里記錄一下自學(xué)過程中覺得重要的壹哺。
1.忽略參數(shù)標(biāo)簽
如果你不希望為某個(gè)參數(shù)添加一個(gè)標(biāo)簽,可以使用一個(gè)下劃線( _ )來代替一個(gè)明確的參數(shù)標(biāo)簽。
func someFunction(_ firstParameterName: Int, secondParameterName: Int) {
// 在函數(shù)體內(nèi),firstParameterName 和 secondParameterName 代表參數(shù)中的第一個(gè)和第二個(gè)參數(shù)值
}
someFunction(1, secondParameterName: 2)
2.默認(rèn)參數(shù)值
你可以在函數(shù)體中通過給參數(shù)賦值來為任意一個(gè)參數(shù)定義默認(rèn)值艘刚。當(dāng)默認(rèn)值被定義后,調(diào)用這 個(gè)函數(shù)時(shí)可以忽略這個(gè)參數(shù)
func someFunction(parameterWithoutDefault: Int, parameterWithDefault: Int = 12) {
// 如果你在調(diào)用時(shí)候不傳第二個(gè)參數(shù),parameterWithDefault 會(huì)值為 12 傳入到函數(shù)體中管宵。
}
someFunction(parameterWithoutDefault: 3, parameterWithDefault: 6) // parameterWithDefault = 6
someFunction(parameterWithoutDefault: 4) // parameterWithDefault = 12
將不帶有默認(rèn)值的參數(shù)放在函數(shù)參數(shù)列表的最前。一般來說,沒有默認(rèn)值的參數(shù)更加的重要,將不帶默認(rèn)值的參
數(shù)放在最前保證在函數(shù)調(diào)用時(shí),非默認(rèn)參數(shù)的順序是一致的,同時(shí)也使得相同的函數(shù)在不同情況下調(diào)用時(shí)顯得更
為清晰攀甚。
3.可變參數(shù)
一個(gè)可變參數(shù)可以接受零個(gè)或多個(gè)值箩朴。函數(shù)調(diào)用時(shí),你可以用可變參數(shù)來指定函數(shù)參數(shù) 可以被傳入不確定數(shù)量的輸入值。通過在變量類型名后面加入( ... )的方式來定義可變參數(shù)秋度。
func arithmeticMean(_ numbers: Double...) -> Double {
var total: Double = 0
for number in numbers {
total += number
}
return total / Double(numbers.count)
}
arithmeticMean(1, 2, 3, 4, 5)
// 返回 3.0, 是這 5 個(gè)數(shù)的平均數(shù)炸庞。 arithmeticMean(3, 8.25, 18.75)
// 返回 10.0, 是這 3 個(gè)數(shù)的平均數(shù)。
一個(gè)函數(shù)最多只能擁有一個(gè)可變參數(shù)
4.在實(shí)例方法中修改值類型
結(jié)構(gòu)體和枚舉是值類型荚斯。默認(rèn)情況下,值類型的屬性不能在它的實(shí)例方法中被修改埠居。但是,如果你確實(shí)需要在某個(gè)特定的方法中修改結(jié)構(gòu)體或者枚舉的屬性,你可以為這個(gè)方法選擇 可變(mutatin g) 行為,然后就可以從其方法內(nèi)部改變它的屬性;并且這個(gè)方法做的任何改變都會(huì)在方法執(zhí)行結(jié)束時(shí)寫回到原始 結(jié)構(gòu)中。
要使用可變方法,將關(guān)鍵字mutating 放到方法的func關(guān)鍵字之前就可以了:
struct Point {
var x = 0.0, y = 0.0
mutating func moveByX(deltaX: Double, y deltaY: Double) {
x += deltaX
y += deltaY }
}
var somePoint = Point(x: 1.0, y: 1.0)
somePoint.moveByX(2.0, y: 3.0)
print("The point is now at (\(somePoint.x), \(somePoint.y))") // 打印 "The point is now at (3.0, 4.0)"
5.UIButton的使用方法
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
let button:UIButton = UIButton(type:.system)
button.frame = CGRect(x:100,y:100,width:70,height:70)
button.setTitle("杰哥開始學(xué)習(xí)swift了", for:.normal)
button.setTitleColor(UIColor.green, for: .normal)
button.titleLabel?.font = UIFont.systemFont(ofSize: 14)
// button.backgroundColor = UIColor.yellow
let iconImage = UIImage(named:"grzx_gd_body_icon_appstorepf@2x")?.withRenderingMode(.alwaysOriginal)
button.setImage(iconImage, for: .normal)
//添加點(diǎn)擊方法事期,方法是并存的
button.addTarget(self, action:#selector(tapped), for: .touchUpInside)
button.addTarget(self, action: #selector(ttt(_:)), for: .touchUpInside)
button.titleLabel?.lineBreakMode = .byTruncatingHead//省略文字開頭滥壕,.byClipping直接將多余的截取掉,byWordWrapping自動(dòng)換行
//當(dāng)設(shè)置自動(dòng)換行后(byWordWrapping 或 byCharWrapping)兽泣,我們可以在設(shè)置 title 時(shí)通過 \n 進(jìn)行手動(dòng)換行
button.titleLabel?.lineBreakMode = .byWordWrapping
button.setTitle("杰哥開始\n學(xué)習(xí)swift了", for: .normal)
self.view.addSubview(button)
}
func tapped() {
print("杰哥R镩佟!唠倦!")
}
func ttt(_ jige:UIButton) {
print("jieii")
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
6.AlertViewController彈出框
func AlertVC() {
let alertVC = UIAlertController(title:"是否彈出", message:"提示框",preferredStyle:.alert)//actionSheet
let alertaction = UIAlertAction(title:"cancel",style:.cancel,handler:nil)
let alertOK = UIAlertAction(title:"ok",style:.destructive,handler:{
action in
print("okokokok")
})
alertVC.addAction(alertOK)
alertVC.addAction(alertaction)
self.present(alertVC,animated: true)
}
彈出框彈出1.5s后隱藏
let alertController = UIAlertController(title: "保存成功!",
message: nil, preferredStyle: .alert)
//顯示提示框
self.present(alertController, animated: true, completion: nil)
//兩秒鐘后自動(dòng)消失
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 1.5) {
self.presentedViewController?.dismiss(animated: false, completion: nil)
}
添加textfield
alertController.addTextField {
(textField: UITextField!) -> Void in
textField.placeholder = "用戶名"
}
alertController.addTextField {
(textField: UITextField!) -> Void in
textField.placeholder = "密碼"
textField.isSecureTextEntry = true
}
7.UILabel使用
func labelLizi() {
let label = UILabel(frame: CGRect(x: 60, y: 60, width: 100, height: 20))
label.text = "杰杰杰杰dfsagdgadslgjsdl;g"
label.textColor = UIColor.green
label.font = UIFont.systemFont(ofSize: 12)
label.textAlignment = .center
label.numberOfLines = 0
label.lineBreakMode = .byTruncatingMiddle//文章過長省略方式
//文字大小自適應(yīng),自動(dòng)改變大小
// label.adjustsFontSizeToFitWidth = true
//富文本 NSFontAttributeName(字體大小称鳞,種類) //NSForegroundColorAttributeName(字體顏色)
// NSBackgroundColorAttributeName(字體背景顏色)
let attributeString = NSMutableAttributedString(string: "杰杰杰杰dfsagdgadslgjsdl;g")
attributeString.addAttribute(NSFontAttributeName, value: UIFont(name: "HelveticaNeue-Bold", size: 15)!,range: NSMakeRange(0,6))
attributeString.addAttribute(NSForegroundColorAttributeName, value: UIColor.blue, range: NSMakeRange(7, 14))
// attributeString.addAttribute(NSBackgroundColorAttributeName, value: UIColor.red, range: NSMakeRange(14, 25))
label.attributedText = attributeString
self.view.addSubview(label)
}
8.tableView以及自定義cell
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = UIColor.white
self.CreateTableView()
}
func CreateTableView(){
let tableView = UITableView.init(frame: CGRect(x: 0, y: 64, width: self.view.frame.width, height: self.view.frame.height - 64))
tableView.delegate = self
tableView.dataSource = self
tableView.register(UITableViewCell.classForCoder(), forCellReuseIdentifier: "cell")
tableView.register(MyTableCell.classForCoder(), forCellReuseIdentifier: "qwert")
self.view.addSubview(tableView)
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 20
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if indexPath.row == 4 {
let cellcx = MyTableCell(style: UITableViewCellStyle.default, reuseIdentifier: "qwert")
cellcx.myTitle.text = "ziyouzizai"
// cellcx.contentView.addSubview(cellcx.myTitle)
return cellcx
} else {
let cellID:String = "cell"
let cell = UITableViewCell(style: UITableViewCellStyle.default, reuseIdentifier: cellID)
cell.textLabel?.text = "this is my first swift tableview"
return cell
}
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 60
}
}
class MyTableCell: UITableViewCell {
// lazy var myTitle:UILabel = {
// let title = UILabel()
// title.font = UIFont.systemFont(ofSize: 13)
// title.textColor = UIColor.lightGray
// title.textAlignment = .left
// title.frame = CGRect(x: 5, y: 5, width: 80, height: 15)
// return title
// }()
var myTitle:UILabel!
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
if !self.isEqual(nil){
myTitle = UILabel(frame: CGRect(x: 5, y: 5, width: 70, height: 15))
myTitle.textColor = UIColor.blue
myTitle.font = UIFont.systemFont(ofSize: 12)
self.contentView.addSubview(myTitle)
}
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func awakeFromNib() {
super.awakeFromNib()
}
在這里說明一下,我在自定義cell中碰到了坑稠鼻,按照原來oc的形式冈止,在cellforrow方法里,我按照條件依次往下寫枷餐,當(dāng)碰到特殊情況時(shí)比如row== 4靶瘸,再寫特殊條件,在swift中是不可以的毛肋,會(huì)出現(xiàn)問題,結(jié)果不對屋剑,原因在于swift是在編譯前就會(huì)計(jì)算運(yùn)行順序润匙,直白說就是他會(huì)依次執(zhí)行,而不會(huì)像oc那樣全部編譯完后唉匾,在運(yùn)行的時(shí)候才會(huì)判斷條件孕讳。
自定義cell里匠楚,如果用懶加載調(diào)用屬性的話,用到了閉包(注釋的)厂财,所以這里沒法添加到cell里芋簿,只能在cellforrow里面添加了
swift自己摸索著學(xué)習(xí),目前還有很多不了解的地方璃饱,也希望和大家一起慢慢學(xué)習(xí)与斤,最后貼一下swift 基礎(chǔ)的一些東西 點(diǎn)擊我