簡單例子:
class TestClass{
var totalNumber:Int = 0{
willSet{
print(newValue)//newValue(自帶屬性)是新傳進(jìn)來的值竖般,這時(shí)totalNumber還沒有變成剛傳進(jìn)來的值
}
didSet {
print(oldValue)//oldValue(自帶屬性)艰亮,這時(shí)totalNumber已經(jīng)改變迄埃,變?yōu)閭鬟M(jìn)來的值
}
}
為了保存右邊中間那個(gè)價(jià)格數(shù)自己還想了很久怎么寫程序,因?yàn)槟莻€(gè)文本是一個(gè)字符串流译,它夾帶有一個(gè)幣種符號(hào)叠赦,剛開始我是這樣保存的,后來發(fā)現(xiàn)每次刷新就要截取出symbol這個(gè)不是數(shù)字的字符除秀,好麻煩
self.oldCurrentPrice = self.labelCurrentPrice.text!
self.labelCurrentPrice.text = "\(symbol)\(curentPrice)"
后來上司教我使用屬性觀察設(shè)計(jì)模式來對currentPrice 進(jìn)行觀察的值
var currentPrice: Double = 0 { //當(dāng)前價(jià)格
willSet {
var marketPriceTrend: MarketPriceTrend
let newPrice = newValue
let trend = newPrice - currentPrice
self.trendImage.hidden = false
if trend > 0 {
//走勢向上
marketPriceTrend = MarketPriceTrend.Up
} else if trend < 0 {
//走勢向下
marketPriceTrend = MarketPriceTrend.Down
} else {
//相等
self.trendImage.hidden = true
marketPriceTrend = MarketPriceTrend.Equal
}
let currentCurrencyType = self.selectedExchangeType.currencyType
let currencyData = CurrencyData.getCurrencyData(currentCurrencyType)!
let symbol = currencyData.symbol
self.labelCurrentPrice.text = "\(symbol)\(newValue.toString())"
//加載圖片升降,這里用的是枚舉返回UIImage
self.trendImage.image = marketPriceTrend.imageTrend
// 設(shè)置字體顏色棍好,也是用枚舉
self.labelCurrentPrice.textColor = marketPriceTrend.trendColor
}
marketPriceTrend枚舉:
/// 市場價(jià)格趨勢
enum MarketPriceTrend {
case Up, Down, Equal
var imageTrend: UIImage {
switch self {
case Up:
return UIImage(named: "btn_market_BZSZ_arrow2")!
case Down:
return UIImage(named: "btn_market_BZSZ_arrow1")!
case Equal:
return UIImage(named: "btn_market_BZSZ_arrow2")!
}
}
var trendColor: UIColor {
switch self {
case Up:
return UIColor(hex: 0xFC461E)
case Down:
return UIColor(hex: 0x149073)
case Equal:
return UIColor(hex: 0xFC461E)
}
}
觀察模式很好用