Goo是基于MVVM模式進行IOS開發的一個美妙的粘合劑,實現View中元素屬性與ViewModel中數據的對接。
轉換器
使用場景:比如在APP中,我們在設計消息的時候,用0代表未讀,1代表已讀,這個時候我們希望UI展示時用圖片顯示已讀和未讀的狀態,這個在Goo中我們需要借助轉換器來實現。
所謂的轉換器就是通過一個條件或者一個類型,轉換成另外一種結果或者類型,主要實現了IValueConverter接口,下面我們通過一個簡單例子來說明。
首先我們來定義一個轉換器
@interface TextConverter : NSObject<ValueConverter>
- (id) convert:(id)valueObject;
@end
#import "TextConverter.h"
@implementation TextConverter
- (id) convert:(id)valueObject{
NSString *s = (NSString *)valueObject;
s= [NSString stringWithFormat:@"label:%@",s ];
return s;
}
使用這個轉換器
[self.inputText bindingWithProperty:@"text" withObject:_vm withDataSource:@"text" withBindingMode:TwoWay];
TextConverter *textConvert = [[TextConverter alloc]init];
[self.hineLbl bindingWithProperty:@"text" withObject:_vm withDataSource:@"text" withBindingMode:OneWay withConverter:textConvert];
實現效果
inputText和hineLbl的text屬性都綁定到VM的text上,這樣通過轉換器hineLbl顯示內容為:在inputText的輸入內容前增加label:
轉換器包含Convert和ConvertBack兩個函數
- Convert函數表示從ViewModel的屬性到UI元素屬性值的轉換。
- ConvertBack函數表示從UI元素屬性值到ViewModel的屬性的值轉換。因此,如果綁定模式是一次綁定或單向綁定,只需實現Convert函數;如果綁定模式是雙向綁定,需要實現Convert和ConvertBack函數。
具體和控件綁定的方式參見上面的代碼
觸發器
觸發器用于監視ViewModel的某一個屬性值或者一組屬性值發生變化后,程序要進行相應的邏輯處理。
使用場景
常見的設計用戶登錄界面時,初期登錄按鈕不可用。一旦輸入用戶名和密碼后登錄按鈕變為可用狀態等等,類似的場景在具體開發中非常普遍。
在Goo中按照數據驅動的原則,觸發器是ViewModel的綁定方法通過Block進行回調。
具體方式參照如下代碼
NSMutableArray *conditions = [[NSMutableArray alloc]init];
[conditions addObject:@"text"];
[conditions addObject:@"backgroundColor"];
[_vm bindingTriggerWithCondition:conditions withDoWithBlock:^{
if([_vm.text isEqualToString:@"456"]&& _vm.backgroundColor ==[UIColor redColor]){
NSLog(@"sdf");
}
}];
如果ViewModel的text屬性等于“456”,backgroundColor等于紅色時即觸發去做某種處理。
目前Goo的版本僅僅是對MVVM實現的一個基本嘗試,后續會繼續維護直到比較成熟后會在Github做第一個版本的發布。