how to open UIViewController when i click RowSelected from UITableViewSource - c#

i want open viewcontroller when i click RowSelected from UITableViewSource
i use this code when i open UIViewController
Any help would be greatly appreciated.
thanks
MainStudUn controller =this.Storyboard.InstantiateViewController("MainStudUn") as MainStudUn;
this.NavigationController.PushViewController(controller, true);
but i have issue when used this code from UITableViewSource
class EmployeesTVS : UITableViewSource
{
List<Employee> employees;
public EmployeesTVS(List<Employee> employees)
{
this.employees = employees;
}
public override UITableViewCell GetCell(UITableView tableView, NSIndexPath indexPath)
{
var cell = (EmployeeCell) tableView.DequeueReusableCell("Cell_id", indexPath);
var employee = employees[indexPath.Row];
cell.updatecell(employee);
return cell;
}
public override nint RowsInSection(UITableView tableview, nint section)
{
return employees.Count;
}
public override void RowSelected(UITableView tableView, NSIndexPath indexPath)
{
var SelectName = employees[indexPath.Row];
Globals.AskX = SelectName.Fullname;
Globals.AnswerX = SelectName.Department;
//OpnWerd();
//MainStudUn controller = this.Storyboard.InstantiateViewController("MainStudUn") as MainStudUn;
//this.NavigationController.PushViewController(controller, true);
}
}

Set the ViewController itself as parameter in the initializing constructor of the dataSource.
in ViewController
this.TableView.Source = new EmployeesTVS(tableItems, this);
in dataSource
AskStud owner; //this is your VC class not ViewController,it's just a sample.
public EmployeesTVS(List<Employee> employees, AskStud owner)
{
this.employees = employees;
this.owner = owner;
}
Usage:
MainStudUn controller =this.owner.Storyboard.InstantiateViewController("MainStudUn") as MainStudUn;
//OR
//UIStoryboard Storyboard = UIStoryboard.FromName("StoryBoardName", null);
//MainStudUn controller = Storyboard.InstantiateViewController("MainStudUn") as MainStudUn;
this.owner.NavigationController.PushViewController(controller, true);

Related

TableView scroll isn't smooth (Xamarin.iOS)

I have table view with images in cells
But when data is shown in TableView and I scroll it, it not smooth. But all images are downloaded I think.
Here is Code for TableView source
public class ExperienceSource : UITableViewSource
{
//UINavigationController instance, to pass it to constructor
private UINavigationController primNav { get; set; }
private UITableView tableView { get; set; }
List<Experience> TableItems;
ExperienceTableViewController owner;
public ExperienceSource(List<Experience> items,ExperienceTableViewController owner, UINavigationController nav)
{
TableItems = items;
this.owner = owner;
primNav = nav;
}
public override nint RowsInSection(UITableView tableview, nint section)
{
if (TableItems.Count == 0)
{
var noDataLabel = new UILabel
{
Text = "No Experiences at your location at this time. Try to change destination",
TextColor = UIColor.Black,
TextAlignment = UITextAlignment.Center,
LineBreakMode = UILineBreakMode.WordWrap,
Lines = 0
};
tableview.BackgroundView = noDataLabel;
tableview.SeparatorStyle = UITableViewCellSeparatorStyle.None;
return TableItems.Count;
}
else
{
tableview.SeparatorStyle = UITableViewCellSeparatorStyle.SingleLine;
return TableItems.Count;
}
}
public override async void RowSelected(UITableView tableView, NSIndexPath indexPath)
{
var selectedExperience = await ExperienceMethods.GetSelectedTour(TableItems[indexPath.Row].id);
if (selectedExperience == "Saved")
{
ExperienceDetailViewController ExperienceDetailController = primNav.Storyboard.InstantiateViewController("ExperienceDetailViewController") as ExperienceDetailViewController;
primNav.PushViewController(ExperienceDetailController, true);
}
else
{
UIAlertController okAlertController = UIAlertController.Create("", "Cannot select this experience", UIAlertControllerStyle.Alert);
okAlertController.AddAction(UIAlertAction.Create("OK", UIAlertActionStyle.Default, null));
}
tableView.DeselectRow(indexPath, true);
}
public override UITableViewCell GetCell(UITableView tableView, NSIndexPath indexPath)
{
var cell = tableView.DequeueReusableCell("cell_id", indexPath) as ExperienceCell;
Experience item = TableItems[indexPath.Row];
cell.UpdateCell(item);
return cell;
}
And I have code for my custom cell in this class
public partial class ExperienceCell : UITableViewCell
{
public ExperienceCell (IntPtr handle) : base (handle)
{
}
internal void UpdateCell(Experience experience)
{
UIImage picture;
try
{
var image_url = "https://xplorpal.com/" + experience.cover_image.img_path + "/300x300/" + experience.cover_image.img_file;
using (var url = new NSUrl(image_url))
using (var data = NSData.FromUrl(url))
picture = UIImage.LoadFromData(data);
ExperienceImage.Image = picture;
}
catch { }
finally
{
ExperienceTitle.Text = experience.title;
ExperiencePrice.Text = "$" + experience.price;
}
}
}
Where can be my problem and how I can optimize scroll of this TableView?
Thank's for help.
I am not familiar with using NSData.FromUrl method inside a TableViewCell, but handling remote images manually is most of the time a bad idea.
You should consider using a library like SDWebImage, that will handle downloading, caching, and assigning the image to your UIImage for you.

Unable to dequeue a cell with identifier cell_id - must register a nib or a class for the identifier

I writing xamarin.ios app and using TableView.
I want to Create a custom cell.
So in the designer, I created it with this properties
I try to use it then in TableSource
Like this
public class ExperienceSource : UITableViewSource
{
Experience[] TableItems;
//NSString cellIdentifier = new NSString("TableCell");
ExperienceController owner;
public ExperienceSource(Experience[] items, ExperienceController owner)
{
TableItems = items;
this.owner = owner;
}
public override nint NumberOfSections(UITableView tableView)
{
return 1;
}
public override nint RowsInSection(UITableView tableview, nint section)
{
return TableItems.Length;
}
public override UITableViewCell GetCell(UITableView tableView, NSIndexPath indexPath)
{
var cell = tableView.DequeueReusableCell("cell_id", indexPath) as ExperienceCell;
//Experience item = TableItems[indexPath.Row];
/*if (cell == null)
{
cell = new ExperienceCell(cellIdentifier);
}*/
cell.UpdateCell(TableItems[indexPath.Row].title, TableItems[indexPath.Row].price);
//---- if there are no cells to reuse, create a new one
/*if (cell == null)
{
cell = new ()(CellIdentifier);
}*/
return cell;
}
}
And Here is class for ExperienceCell
public partial class ExperienceCell : UITableViewCell
{
public ExperienceCell (IntPtr handle) : base (handle)
{
}
internal void UpdateCell(string title, string price)
{
ExperienceTitle.Text = title;
ExperincePrice.Text = price;
}
}
When I run app, I got this error
unable to dequeue a cell with identifier cell_id - must register a nib
or a class for the identifier or connect a prototype cell in a
storyboard
How I can fix this?
Thank's for help.
You are missing the registration of the UITableViewCell in the UITableView.
Please add something like this in your ViewController (the important part is the RegisterNibForCellReuse sentence):
public override void ViewDidLoad()
{
base.ViewDidLoad();
MyTableView.RegisterNibForCellReuse(UINib.FromName(nameof(ExperienceCell), NSBundle.MainBundle), "cell_id");
MyTableView.Source = new ExperienceSource(..., ...);
// .. your code
}
This is a necessary step when you declare your UITableViewCells outside the UITableView.

How to break reference cycle between view controller and data source

Consider this simple example:
public partial class TableViewController : UITableViewController
{
public TableViewController (IntPtr handle) : base (handle)
{
}
protected override void Dispose (bool disposing)
{
Console.WriteLine (String.Format ("{0} controller disposed - {1}", this.GetType (), this.GetHashCode ()));
base.Dispose (disposing);
}
public override void ViewDidLoad ()
{
//TableView.Source = new TableSource(this);
TableView.Source = new TableSource();
}
}
public class TableSource : UITableViewSource {
private TableViewController controller;
string CellIdentifier = "TableCell";
public TableSource ()
{
}
public TableSource (TableViewController controller)
{
this.controller = controller;
}
public override nint RowsInSection (UITableView tableview, nint section)
{
return 1;
}
public override UITableViewCell GetCell (UITableView tableView, 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 = "test";
return cell;
}
}
I've noticed that the view controller (TableViewController) is never released. The table view controller has a reference to the data source, but the data source also has a reference to the table view controller.
With TableView.Source = new TableSource(); the view controller gets released, with TableView.Source = new TableSource(this); it's not.
How should this reference cycle be broken so that everything get released?
Edit:
Now I tried the WeakReference:
Through using a WeakReference the Dispose method is called, when the view controller is popped off the navigation stack.
In ViewDidLoad:
TableView.Source = new TableSource(new WeakReference<TableViewController> (this));
In the datasource:
private WeakReference<TableViewController> controller;
public TableSource (WeakReference<TableViewController> controller)
{
this.controller = controller;
}
I built this into my real project, but how can I access my controller? I get the message
Type 'System.WeakReference' does not contain a definition for 'xxx' and no extension method 'xxx' of type 'System.WeakReference' could be found. Are you missing an assembly reference?
You work with Xamarin, as I see? Have you tried WeakReference?
https://msdn.microsoft.com/en-us/library/system.weakreference(v=vs.110).aspx
PS:
private WeakReference weakController;
to set:
this.weakController = new WeakReference(controller);
to get:
if (weakController.isAlive)
{
TableViewController controller = weakController.Target as TableViewController;
}
change
public partial class TableViewController : UITableViewController
to
public partial class TableViewController : UITableViewController, UITableViewSource
and in ViewDidLoad just do
self.TableView.Source = self;
the source property is a weak reference internally already so your have no problem of managing that. It is a convenience property to make the tbaleviewcontroller the delegate and datasource altogether. (Just like you would in native iOS)
You can move the methods into the controller itself which would be less of a hassle than WeakReference. Then mark them with export attribute which then allows you to set the UITableView.WeakDataSource property to the controller itself.
[Export("tableView:numberOfRowsInSection:")]
public nint RowsInSection (UITableView tableview, nint section)
[Export("tableView:cellForRowAtIndexPath:")]
public UITableViewCell GetCell (UITableView tableView, NSIndexPath indexPath)
Once they are moved you can attach the datasource:
public override void ViewDidLoad ()
{
TableView.WeakDataSource = this;
}

How to access main UIViewController from UITableView RowSelect Event Monotouch?

I have a UITAbleView on my main ViewController. Tableview is subclasses as seen below. When a user selects a row I want to switch to a new view by calling a routine on the main ViewController. However, i'm not able to access my main viewcontroller from the subclass. How should I go about this?
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;
}
public override UITableViewCell GetCell(UITableView tableView, MonoTouch.Foundation.NSIndexPath indexPath)
{
UITableViewCell cell = tableView.DequeueReusableCell(cellIdentifier);
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);
//Call routine in the main view controller to switch to a new view
}
}
I happened to come across this post after finding and commenting on a similar post:
Xamarin UITableView RowSelection
While passing an instance of your UIViewController to your TableSource is one way to solve this problem, it does have its drawbacks. Mainly that you've tightly coupled your TableSource to that particular type of UIViewController.
What I would suggest instead is to create an EventHandler in your UITableViewSource like so:
public event EventHandler ItemSelected;
I would also set up a getter property for the selected item:
private selectedItem
public MyObjectType SelectedItem{
get{
return selectedItem;
}
}
I would then update the RowSelected method like so:
public override void RowSelected(UITableView tableView, NSIndexPath indexPath)
{
selectedItem = tableItems[indexPath.Row];
ItemSelected(this, EventArgs.Empty);
}
Your UIViewController could then listen to the ItemSelected event and do whatever it needs. This allows you to reuse your UITableViewSource for multiple Views and ViewControllers.
Add it to your .ctor, e.g.
public TableSource(string[] items)
becomes:
public TableSource(string[] items, UIViewController ctl)
then keep a reference to it:
public TableSource(string[] items, UIViewController ctl)
{
tableItems = items;
controller = ctl;
}
and use it in your RowSelected call:
public override void RowSelected(UITableView tableView, NSIndexPath indexPath)
{
new UIAlertView("Row Selected", tableItems[indexPath.Row], null, "OK", null).Show();
tableView.DeselectRow(indexPath, true);
controller.DoWhatYouNeedWithIt ();
}
NSNotifications might be another option.
So in the RowSelected you post a notification:
NSNotificationCenter.DefaultCenter.PostNotificationName("RowSelected", indexPath);
And in the view controller you add an observer for the notification:
public override void ViewDidLoad()
{
base.ViewDidLoad();
NSNotificationCenter.DefaultCenter.AddObserver(new NSString("RowSelected"), RowSelected);
}
void RowSelected(NSNotification notification)
{
var indexPath = notification.Object as NSIndexPath;
// Do Something
}

How to navigate to a view controller when a specific row is selected in tableview?

I have a navigation controller. Inside it i have a view controller that has a button. When the button is clicked a popover shows with a tableview of items.
When an item is selected i want to either navigate to a different view controller or open up a view controller on top of the current one.
I hope i've made my objectives clear.
Below is my current code:
private UITableView tableView;
private List list;
private class TableViewDelegate : UITableViewDelegate
{
private List<string> list;
public TableViewDelegate(List<string> list)
{
this.list = list;
}
public override void RowSelected (
UITableView tableView, NSIndexPath indexPath)
{
//THIS IS WHERE I AM CURRENTLY PUTTING THE NAVIGATION CONTROLLER PUSHVIEWCONTROLLER. BUT ITS NOT WORKING !!!
}
}
private class TableViewDataSource : UITableViewDataSource
{
static NSString kCellIdentifier =
new NSString ("MyIdentifier");
private List<string> list;
public TableViewDataSource (List<string> list)
{
this.list = list;
}
public override int RowsInSection (
UITableView tableview, int section)
{
return list.Count;
}
public override UITableViewCell GetCell (
UITableView tableView, NSIndexPath indexPath)
{
UITableViewCell cell =
tableView.DequeueReusableCell (
kCellIdentifier);
if (cell == null)
{
cell = new UITableViewCell (
UITableViewCellStyle.Default,
kCellIdentifier);
}
cell.TextLabel.AdjustsFontSizeToFitWidth = true;
cell.TextLabel.Font = UIFont.FromName("Helvetica", 14.0f);
cell.TextLabel.Text = list[indexPath.Row];
return cell;
}
}
in monotouch you should use
class TableDelegate : UITableViewDelegate
{
public override void RowSelected (UITableView tableView, NSIndexPath indexPath)
{
this.YourNavigationController.PushViewController(yourViewController,true);
}
}
also i recommend you to use monotouch.dialog
in your table source declare an event like this:
public class TableSourceAnimales : UITableViewSource
{
public event RowSelectedEventHandler RowSelectedEvent;
public override void RowSelected (UITableView tableView, NSIndexPath indexPath)
{
if (this.RowSelectedEvent != null) {
RowSelectedEvent (indexPath);
}
}
}
and in your uiviewcontroller like this
namespace yournamespace
public delegate void RowSelectedEventHandler(MonoTouch.Foundation.NSIndexPath indexpath);
public partial class yourclass : UIViewController
{
public override void ViewDidLoad ()
{
TableViewDataSource tablelist = new TableViewDataSource (yourlist);
table.Source = tablelist;
table.ReloadData ();
table.RowSelectedEvent += tablelist_RowSelectedEvent;
}
public void tablelist_RowSelectedEvent (NSIndexPath indexpath)
{
this.YourNavigationController.PushViewController(yourViewController,true);
//or what you want to do
}
}
Check which row is clicked in this function:
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
And then show your view controller.
This will do the trick:
- (void)tableView:(UITableView *)tblView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
[self.tableView deselectRowAtIndexPath:indexPath animated:YES];
YourViewController *vc = [[[YourViewController alloc] initWithNibName:#"YourViewController" bundle:[NSBundle mainBundle]] autorelease];
[self.navigationController pushViewController:vc animated:YES];
}
Something like this in mono:
public override void RowSelected (UITableView tableView, NSIndexPath indexPath)
{
var DetailViewController = new DetailViewController ();
// Pass the selected object to the new view controller.
controller.NavigationController.PushViewController(DetailViewController, true);
}
actually its like in Obj-C only the syntax is a bit different. Try to do it yourself next time, its easy.

Categories