我們這個(gè)App要實(shí)現(xiàn)輸入兩個(gè)數(shù),求和的簡(jiǎn)單操作寸癌,我希望通過(guò)這個(gè)App表述MVC到底是一種怎樣的程序編寫方式粪糙。
首先我們來(lái)畫UI,打開(kāi)StoryBoard像捶,拖動(dòng)控件,加好AutoLayOut桩砰,結(jié)果如圖:
回到我們的UIViewController中拓春,添加IBOutlet以及IBAction,實(shí)例化View中的控件亚隅。
import UIKit
class ViewController: UIViewController {
@IBOutlet var resultLabel: UILabel!
@IBOutlet var textFiledOne: UITextField!
@IBOutlet var textFiledTwo: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func startCalculate(_ sender: Any) {
}
}
接下來(lái)就是實(shí)現(xiàn)加法運(yùn)算硼莽,初學(xué)者非常容易在
@IBAction func startCalculate(_ sender: Any) {
}
這個(gè)函數(shù)中直接把加法的運(yùn)算過(guò)程寫進(jìn)去,這是違反MVC設(shè)計(jì)模式的煮纵,Controller 并不負(fù)責(zé)處理數(shù)據(jù)懂鸵,我們應(yīng)該新建一個(gè)Swift文件,寫一個(gè)CaculatorBrain類行疏,用private隱藏外界不能夠改變的變量和函數(shù)匆光,僅提供一個(gè)初始化方法和一個(gè)API借口,完成所有的運(yùn)算過(guò)程酿联。
我們可以看出终息,從textFiled輸入的值是一個(gè)String類型的,而加法是兩個(gè)Double做運(yùn)算贞让,運(yùn)算結(jié)束后周崭,又要把結(jié)果的Double值轉(zhuǎn)換成String,顯示在resultLabel上喳张。我們需要把所有的類型轉(zhuǎn)換以及計(jì)算過(guò)程全部封裝進(jìn)Model中续镇。
import Foundation
class CalculaterBrain{
private var numbOne:Double!
private var numbTwo:Double!
init(numbOne:String?,numbTwo:String?) {
self.numbOne = (numbOne! as NSString).doubleValue
self.numbTwo = (numbTwo! as NSString).doubleValue
}
func calculate()->String{
return String(numbOne + numbTwo)
}
}
我們僅給外界預(yù)留了一個(gè)初始化方法以及一個(gè)運(yùn)算求和的函數(shù)calculate(),下面我們?cè)赨IViewController中實(shí)例化這個(gè)model销部,并完成我們的demo
import UIKit
class ViewController: UIViewController {
@IBOutlet var resultLabel: UILabel!
@IBOutlet var textFiledOne: UITextField!
@IBOutlet var textFiledTwo: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func startCalculate(_ sender: Any) {
let calculator = CalculaterBrain(numbOne: textFiledOne.text, numbTwo: textFiledTwo.text)
resultLabel.text = calculator.calculate()
}
}