我们经常会在两个类中实现传值,或者在两个页面中传值,这个时候我们有时候用到了代理,运用代理的步骤如下所示:
第一步,我们要在页面一(也就是将要传值的页面)定一个委托(也就是代理),格式如下:
public delegate void SelectRow(nint row);
格式如下:delegate+返回值类型+函数名;这里函数里面值的类型是和传递的内容类型一样的。
第二步,申明一个代理
public event SelectRow selectRow;
第三步,调用代理
selectRow (indexPath.Row);
我们这里只需要,然后再另一个页面实现代理即可(我这里是在实例化的时候就实现了代理)
this.tableview.Source = new MyTableviewsource (delegate(nint row){
label.Text="选中第"+row+"行";
});
那么,我们在构造函数的时候,必须写一个带参数的构造方法。
public MyTableviewsource (SelectRow selectRow)
{
data = new List<string> (){"0","1","2","3","4","5","6","7","8","9","10","11" };
this.selectRow = selectRow;
}
代码如下:
using System;
using UIKit;
namespace Delegate
{
public partial class ViewController : UIViewController
{
UITableView tableview;
UILabel label;
public ViewController (IntPtr handle) : base (handle)
{
}
public override void ViewDidLoad ()
{
base.ViewDidLoad ();
// Perform any additional setup after loading the view, typically from a nib.
tableview=new UITableView(new CoreGraphics.CGRect(0,0,UIScreen.MainScreen.Bounds.Width,UIScreen.MainScreen.Bounds.Height-40));
this.tableview.Source = new MyTableviewsource (delegate(nint row){
label.Text="选中第"+row+"行";
});
label = new UILabel (new CoreGraphics.CGRect(0,UIScreen.MainScreen.Bounds.Height-40,UIScreen.MainScreen.Bounds.Width,40));
label.BackgroundColor = UIColor.DarkGray;
label.TextColor = UIColor.Red;
this.View.AddSubviews (tableview,label);
}
public override void DidReceiveMemoryWarning ()
{
base.DidReceiveMemoryWarning ();
// Release any cached data, images, etc that aren't in use.
}
}
}
using System;
using UIKit;
using Foundation;
using System.Collections.Generic;
namespace Delegate
{
// public void delegate SelectRow(nint row);
public class MyTableviewsource:UITableViewSource
{
List <string> data;
string cellReusID="cellReusID";
public delegate void SelectRow(nint row);
public event SelectRow selectRow;
public MyTableviewsource (SelectRow selectRow)
{
data = new List<string> (){"0","1","2","3","4","5","6","7","8","9","10","11" };
this.selectRow = selectRow;
}
public override UITableViewCell GetCell (UITableView tableView, NSIndexPath indexPath)
{
UITableViewCell cell = tableView.DequeueReusableCell (cellReusID);
if (cell == null) {
cell = new UITableViewCell (UITableViewCellStyle.Default, cellReusID);
}
cell.TextLabel.Text=data[(int)indexPath.Row];
return cell;
}
public override void RowSelected (UITableView tableView, NSIndexPath indexPath)
{
selectRow (indexPath.Row);
}
public override nint RowsInSection (UITableView tableview, nint section)
{
return data.Count;
}
}
}