MonoTouch是利用C#語言進行iOS開發的跨平台解決方案,包括支持iPhone/iPad的開發,目前也支持了最新的iOS 6的版本。
官方地址:http://xamarin.com/
github Sample:https://github.com/xamarin/monotouch-samples
app應用:http://xamarin.com/apps/all
MonoTouch可以利用C# 語言進行iOS開發,意味着作為.Net程序員,也可以很容易地進行iOS開發。當然,能夠理解objective-c語法對你的iOS學習也是很有幫助的。
本篇文章,主要教你如何利用MonoTouch來綁定原生的Obj-C靜態庫,並且直接調用靜態庫里面的方法完成實現。
首先利用xcode創建一個原生的靜態庫:
Project中加入MBProgressHUD的兩個文件(MBProgressHUD是個等待加載特效框架,github:https://github.com/jdg/MBProgressHUD)
然后編譯下,默認地,在/Library/Developer/Xcode/DerivedData可以找到BindingLibraryl的應用,libBindingLibrary.a
接着打開MonoDevelop,新建一個BindingLibrary解決方案,添加一個BindingLibrarySDK項目:
選擇“MonoTouch Binding Project",這個項目專門用來綁定a native library的。
然后,將libBindingLibrary.a添加到該項目中去,並且,你會發現在項目中它會自動產生一個叫做libBindingLibrary.linkwith.cs的文件:
using MonoTouch.ObjCRuntime;
[assembly: LinkWith ( " libBindingLibrary.a ", LinkTarget.Simulator, ForceLoad = true)]
這樣就實現了libBindingLibrary.a靜態庫的導入,此實現類似於DllImport引用非C#(例如C++)動態庫的導入。
你可以發現項目中自動產生兩個文件,ApiDefinition.cs以及StructsAndEnums.cs文件,ApiDefintion.cs主要作為原生類定義的相關映射。
具體文檔可以查看:Binding Objective-C Types
這里編寫代碼:
interface MBProgressHUD
{
[Static, Export( " showHUDAddedTo:animated: ")]
MBProgressHUD ShowHUDAddedTo (UIView view, bool animated);
[Export( " show: ")]
void Show ( bool animated);
[Export( " hide: ")]
void Hide ( bool animated);
[Export( " hide:afterDelay: ")]
void Hide ( bool animated, double delay);
[Export ( " labelText ", ArgumentSemantic.Copy)]
String LabelText { get; set; }
其中對應的原生接口有:
- ( void)show:(BOOL)animated;
- ( void)hide:(BOOL)animated;
- ( void)hide:(BOOL)animated afterDelay:(NSTimeInterval)delay;
@property (copy) NSString *labelText;
其中BaseType為它的繼承類型為UIView,對應於原生的MBProgressHUD類的基類為UIView;
Export為導入的方法名稱,Static說明它作為一個靜態的方式;
ArgumentSematic是它的參數類型為Copy;
然后就可以直接編譯BindingLibrarySDK了,生成一個BindingLibrarySDK.dll
現在,新建一個新的iOS項目:
這里,我選擇一個單窗口的iphone應用程序。
把剛剛的BindingLibrarySDK.dll引用進來:
接着,我在xib文件設計一個按鈕控件,生成點擊事件的代碼:
在點擊事件代碼中,實現:
{
BindingLibrarySDK.MBProgressHUD hud = BindingLibrarySDK.MBProgressHUD.ShowHUDAddedTo( this.View, true);
hud.Show( true);
hud.LabelText = ;
hud.Hide( true, 1); // hide hud after 1s
}
最后,運行程序,查看效果:
點擊按鈕,顯示加載效果框,等1秒之后,效果框消失。
這樣就通過MonoTouch實現了綁定原生Obj-C靜態庫,調用了相關的原生方法。
本文例子:https://github.com/sunleepy/monotouch_binding