简单例子:
class TestClass{
var totalNumber:Int = 0{
willSet{
print(newValue)//newValue(自带属性)是新传进来的值,这时totalNumber还没有变成刚传进来的值
}
didSet {
print(oldValue)//oldValue(自带属性),这时totalNumber已经改变,变为传进来的值
}
}
为了保存右边中间那个价格数自己还想了很久怎么写程序,因为那个文本是一个字符串,它夹带有一个币种符号,刚开始我是这样保存的,后来发现每次刷新就要截取出symbol这个不是数字的字符,好麻烦
self.oldCurrentPrice = self.labelCurrentPrice.text!
self.labelCurrentPrice.text = "\(symbol)\(curentPrice)"
后来上司教我使用属性观察设计模式来对currentPrice 进行观察的值
var currentPrice: Double = 0 { //当前价格
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
// 设置字体颜色,也是用枚举
self.labelCurrentPrice.textColor = marketPriceTrend.trendColor
}
marketPriceTrend枚举:
/// 市场价格趋势
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)
}
}
观察模式很好用