IOS开发笔记

导航栏的设置标题
publicHelloWorldScreen () : base ("HelloWorldScreen", null)
 { this.Title="World!"; }
隐藏导航栏
public override void ViewWillAppear (bool animated) { base.ViewWillAppear (animated); this.NavigationController.SetNavigationBarHidden (true, animated);
}
public override void ViewWillDisappear (bool animated) { base.ViewWillDisappear (animated); this.NavigationController.SetNavigationBarHidden (false, animated);
}
按钮事件
aButton.TouchUpInside+= (o,s) => { Console.WriteLine("button touched"); };
匿名方法
aButton.TouchUpInside+=delegate { Console.WriteLine ("button touched"); };

获取按钮touchDown事件
UIButton button =MakeTheButton ();
button.TouchDown+=delegate { Console.WriteLine ("Touched"); };

lambda表达式方式获取touchDown事件
button.TouchTown+= () => { Console.WriteLine ("Touched"); };
多个按钮使用相同的程序处理
voidhandler (object sender, EventArgs args) {
 if (sender == button1)
Console.WriteLine ("button1");
else
Console.WriteLine ("some other button"); }
button1.TouchDown+= handler;
button2.TouchDown+= handler;
一段代码处理多个事件
button.AddTarget (handler, UIControlEvent.TouchDown|UIControl.TouchCancel);
lambda方式处理多个事件
button.AddTarget (()=>Console.WriteLine ("An event happened"), UIControlEvent.TouchDown|UIControl.TouchCancel);
连接特定的对象实例(如何是继承基类的实例方法,则需public)
[Export ("MySelector")]
voidMyObjectiveCHandler () { Console.WriteLine ("Hello!"); }
 // In some other place:
button.AddTarget (this, newSelector ("MySelector"), UIControlEvent.TouchDown);
地图操作,建立一个委托
public class SampleMapDelegate : MKMapViewDelegate{ public override void DidSelectAnnotationView ( MKMapView mapView, MKAnnotationView annotationView) {
var sampleAnnotation=annotationView.AnnotationasSampleMapAnnotation;
 if (sampleAnnotation !=null) {
//demo accessing the coordinate of the selected annotation to
//zoom in on it
mapView.Region=MKCoordinateRegion.FromDistance(sampleAnnotation.Coordinate, 500, 500);
//demo accessing the title of the selected annotation
Console.WriteLine ("{0} was tapped", sampleAnnotation.Title); } } }
调用地图委托
public partial class Protocols_Delegates_EventsViewController : UIViewController{
SampleMapDelegate _mapDelegate;
 ...
public override void ViewDidLoad () {
base.ViewDidLoad ();
//set the map's delegate
_mapDelegate =newSampleMapDelegate ();
map.Delegate= _mapDelegate;
... }
 classSampleMapDelegate : MKMapViewDelegate
{ ... }
}
lambda调用地图委托
map.DidSelectAnnotationView+= (s,e) => {
var sampleAnnotation = e.View.AnnotationasSampleMapAnnotation;
if (sampleAnnotation !=null) { //demo accessing the coordinate of the selected annotation to
//zoom in on it
mapView.Region=MKCoordinateRegion.FromDistance (sampleAnnotation.Coordinate, 500, 500);
//demo accessing the title of the selected annotation
Console.WriteLine ("{0} was tapped", sampleAnnotation.Title); } };
线程,再主线程中调用该委托
MyThreadedRoutine () {
var result =DoComputation ();
//// we want to update an object that is managed by the main
// thread; To do so, we need to ensure that we only access
// this from the main thread:
InvokeOnMainThread (delegate {
 label.Text="The result is: "+ result; }); }
线程的安全
voidMyThreadStart (object arg) {
using (var ns =newNSAutoReleasePool ()){
// Your code goes here. } }
图片,根据分辨率选择图片
this.TabBarItem.Image=UIImage.FromBundle ("Images/first");
异步加载图片
this.TabBarItem.Image=UIImage.FromFile("Images/second.png");
目录下的子目录
var directories =Directory.EnumerateDirectories("./");
foreach (var directory in directories) { Console.WriteLine(directory); }
读取文本文件
var text =File.ReadAllText("TestData/ReadMe.txt");
Console.WriteLine(text);
xml系列化
using (TextReader reader =newStreamReader("./TestData/test.xml")) { XmlSerializer serializer =newXmlSerializer(typeof(MyObject));
var xml = (MyObject)serializer.Deserialize(reader); }
创建文件
var documents =Environment.GetFolderPath (Environment.SpecialFolder.MyDocuments);
var filename =Path.Combine (documents, "Write.txt");
File.WriteAllText(filename, "Write this text into a file");
创建目录
var documents =Environment . GetFolderPath ( Environment . SpecialFolder . MyDocuments );
 var directoryname =  Path . Combine (documents, "NewDirectory" );
 Directory . CreateDirectory (directoryname);

创建文件 使用构建路径
var documents =Environment.GetFolderPath (Environment.SpecialFolder.MyDocuments);
var library =Path.Combine (documents, "..", "Library");
 var filename =Path.Combine (library, "WriteToLibrary.txt"); File.WriteAllText(filename, "Write this text into a file in Library");
创建目录 使用构建路径
var documents =  Environment . GetFolderPath ( Environment . SpecialFolder . MyDocuments );
 var library =  Path . Combine (documents, ".." , "Library" );
 var directoryname =  Path . Combine (library, "NewLibraryDirectory" );
 Directory . CreateDirectory (directoryname);
文件缓存
var documents =  Environment . GetFolderPath ( Environment . SpecialFolder . MyDocuments );
 var cache =  Path . Combine (documents, ".." , "Library" , "Caches" );
 var tmp =  Path . Combine (documents, ".." , "tmp" );
备份时跳过此文件
It would need to be re-created after a restore or re-install" ); NSFileManager . SetSkipBackupAttribute (filename, true );
// backup will be skipped for this file
文件不会被备份(TRUE的时候)
NSFileManager.SetSkipBackupAttribute (filename, false);
 // file will be backed-up
绘制UIView子类
publicclassTriangleView : UIView{
public override void Draw (RectangleF rect) { base.Draw (rect); } }
绘制图形
//get graphics context
using ( CGContext g = UIGraphics . GetCurrentContext ()){
//set up drawing attributes
g. SetLineWidth ( 4 );
UIColor . Purple . SetFill ();
UIColor . Black . SetStroke (); //create geometry to graphics context and draw it
g. AddPath (path);
g. DrawPath ( CGPathDrawingMode . FillStroke ); }
渐变填充
// add the path back to the graphics context so that it is the current pathg.AddPath (path);
// set the current path to be the clipping
pathg.Clip ();
整体渐变代码
// the color space determines how Core Graphics interprets color information                         
using (CGColorSpace rgb =CGColorSpace.CreateDeviceRGB()) {
CGGradient gradient =newCGGradient (rgb, newCGColor[] { UIColor.Blue.CGColor, UIColor.Yellow.CGColor });
// draw a linear gradient
g.DrawLinearGradient (gradient, newPointF (path.BoundingBox.Left, path.BoundingBox.Top),newPointF (path.BoundingBox.Right, path.BoundingBox.Bottom), CGGradientDrawingOptions.DrawsBeforeStartLocation); }
绘直线用虚线绘制
//use a dashed
lineg.SetLineDash (0, newfloat[]{10, 4});
颠倒图片
public  override  void  Draw ( RectangleF rect)
 {
     base . Draw (rect);
 
    using ( CGContext g =  UIGraphics . GetCurrentContext ()){
         g. DrawImage (rect,
             UIImage . FromFile ( "MyImage.png" ). CGImage );
     }
 }
图片通过CTM变正
public override void Draw (RectangleF rect) {
base.Draw (rect);
using(CGContext g =UIGraphics.GetCurrentContext ()){
// scale and translate the CTM so the image appears upright
g.ScaleCTM (1, -1); g.TranslateCTM (0, -Bounds.Height);
g.DrawImage (rect, UIImage.FromFile ("MyImage.png").CGImage); } }
图片加文字
public override void Draw ( RectangleF rect) {
base . Draw (rect);
 // image drawing code omitted for brevity ...
// translate the CTM by the font size so it displays on screen
float fontSize = 35 f;
g. TranslateCTM ( 0 , fontSize);
// set general-purpose graphics set text specific graphics state
g. SetTextDrawingMode ( CGTextDrawingMode . FillStroke );
g. SelectFont ( "Helvetica" , fontSize, CGTextEncoding . MacRoman );
// show the text
g. ShowText ( "Hello Core Graphics" ); }
将图绘制进内存
UIImage DrawTriangle () {
UIImage triangleImage;
//push a memory backed bitmap context on the context stack
UIGraphics . BeginImageContext ( new SizeF ( 200.0 f, 200.0 f)); /
/get graphics context
using ( CGContext g = UIGraphics . GetCurrentContext ()){
//set up drawing attributes
g. SetLineWidth ( 4 );
UIColor . Purple . SetFill ();
UIColor . Black . SetStroke ();
//create geometry to graphics context and draw it
g. AddPath (path);
g. DrawPath ( CGPathDrawingMode . FillStroke );
//get a UIImage from the context
triangleImage = UIGraphics . GetImageFromCurrentImageContext (); } return triangleImage; }
UIImageView过度
UIView . Transition ( fromView: view1, toView:() = > { Console . WriteLine ( "transition complete" ); });
图片来回动
pt = imgView.Center;
UIView.Animate ( duration: 2, delay: 0, options: UIViewAnimationOptions.CurveEaseInOut|UIViewAnimationOptions.Autoreverse, animation: () => { imgView.Center=newPointF (View.Bounds.GetMaxX () - imgView.Frame.Width/2, pt.Y);},
completion: () => { imgView.Center= pt; } );
C#添加一个视图UILabel控制器
UILabel label1;
public override void ViewDidLoad () {
    base.ViewDidLoad ();
    var frame = new RectangleF(10, 10, 300, 30);
    label1 = new UILabel(frame);
    label1.Text = "New Label";
    View.Add (label1);
}
弹出窗口
UIAlertView alert = new UIAlertView ("Alert Title", "Choose from two buttons", null, "OK", new string[] {"Cancel"});
alert.Clicked += (s, b) => {
    label1.Text = "Button " + b.ButtonIndex.ToString () + " clicked";
    Console.WriteLine ("Button " + b.ButtonIndex.ToString () + " clicked");
};
alert.Show();
弹框垂直布局
UIAlertView alert = new UIAlertView () {
  Title = "custom buttons alert",
  Message = "this alert has custom buttons"
};
alert.AddButton("OK");
alert.AddButton("custom button 1");
alert.AddButton("Cancel");
// last button added is the 'cancel' button (index of '2')
alert.Clicked += delegate(object a, UIButtonEventArgs b) {
    Console.WriteLine ("Button " + b.ButtonIndex.ToString () + " clicked"); };
alert.Show ();

使用UITableView
public override void ViewDidLoad ()
{
    base.ViewDidLoad ();
    table = new UITableView(View.Bounds); // defaults to Plain style
    string[] tableItems = new string[] {"Vegetables","Fruits","Flower Buds","Legumes","Bulbs","Tubers"};
    table.Source = new TableSource(tableItems);
    Add (table);
}
public class TableSource : UITableViewSource {
    string[] tableItems;
    string cellIdentifier = "TableCell";
    public TableSource (string[] items)
    {
        tableItems = items;
    }
    public override int RowsInSection (UITableView tableview, int section)
    {
        return tableItems.Length;
    }
UITableViewSource的使用
    public override UITableViewCell GetCell (UITableView tableView, MonoTouch.Foundation.NSIndexPath indexPath)
    {
        UITableViewCell cell = tableView.DequeueReusableCell (cellIdentifier);
        // if there are no cells to reuse, create a new one
        if (cell == null)
            cell = new UITableViewCell (UITableViewCellStyle.Default, cellIdentifier);
        cell.TextLabel.Text = tableItems[indexPath.Row];
        return cell;
    }
}
点击一个之后的操作
public override void RowSelected (UITableView tableView, NSIndexPath indexPath)
{
    new UIAlertView("Row Selected", tableItems[indexPath.Row], null, "OK", null).Show();
    tableView.DeselectRow (indexPath, true); // normal iOS behaviour is to remove the blue highlight
}
添加索引
indexedTableItems = new Dictionary>();
foreach (var t in items) {
    if (indexedTableItems.ContainsKey (t[0].ToString ())) {
        indexedTableItems[t[0].ToString ()].Add(t);
    } else {
        indexedTableItems.Add (t[0].ToString (), new List() {t});
    }
}
keys = indexedTableItems.Keys.ToArray ();

posted @ 2015-04-24 12:10  成败在我手  阅读(255)  评论(0编辑  收藏  举报