I am very new to XCode and Monotouch development. I am trying to add multiple tabs in root view (Master-Detail application). I am using Mono for development and xCode 4 for UI design. For example, one tab shows list of employees and another tab shows list of departments.
I removed the default table view in the rootviewController.xib file and replaced with tabbedview but I cant get new table view for each tab working.
I would appreciate if anyone can show me the correct way of doing this.
UPDATED: I use the code below to add 2 tabs and 2 table view. One is to hold "Securities" and the other one to hold the "Indicators"
using System;
using System.Drawing;
using MonoTouch.Foundation;
using MonoTouch.UIKit;
using System.Collections.Generic;
namespace ChartQ
{
public partial class RootViewController : UITabBarController
{
public DetailViewController DetailVC { get; set; }
private List<SecurityInfo> listSecInfo = new List<SecurityInfo>();
private List<Indicator> listIndicator = new List<Indicator>();
public RootViewController () : base ("RootViewController", null)
{
this.Title = NSBundle.MainBundle.LocalizedString ("Securities", "Securities");
//this.ClearsSelectionOnViewWillAppear = false;
this.ContentSizeForViewInPopover = new SizeF (100f, 200f);
//this.ContentSizeForViewInPopover = new SizeF (320f, 600f);
// Custom initialization
}
public override void ViewDidLoad ()
{
base.ViewDidLoad ();
//Read data from Database..
UITableViewController secController = new UITableViewController();
UITableViewController IndiController = new UITableViewController();
this.AddChildViewController(secController);
this.AddChildViewController(IndiController);
SQLLiteDatabase db = new SQLLiteDatabase();
listSecInfo = db.ReadSecurities();
listIndicator = db.ReadIndicator();
//TableView.Source = new SecuritiesDataSource (this);
secController.TableView.Source = new SecuritiesDataSource (this);
secController.TableView.SelectRow (NSIndexPath.FromRowSection (0, 0), false, UITableViewScrollPosition.Middle);
IndiController.TableView.Source = new IndicatorDataSource (this);
IndiController.TableView.SelectRow (NSIndexPath.FromRowSection (0, 0), false, UITableViewScrollPosition.Middle);
}
public override bool ShouldAutorotateToInterfaceOrientation (UIInterfaceOrientation toInterfaceOrientation)
{
// Return true for supported orientations
return true;
}
public override void DidReceiveMemoryWarning ()
{
// Releases the view if it doesn't have a superview.
base.DidReceiveMemoryWarning ();
// Release any cached data, images, etc that aren't in use.
}
public override void ViewDidUnload ()
{
base.ViewDidUnload ();
// Clear any references to subviews of the main view in order to
// allow the Garbage Collector to collect them sooner.
//
// e.g. myOutlet.Dispose (); myOutlet = null;
ReleaseDesignerOutlets ();
}
class SecuritiesDataSource : UITableViewSource
{
static NSString cellIdentifier = new NSString ("CellId");
RootViewController controller;
public SecuritiesDataSource (RootViewController controller)
{
this.controller = controller;
}
// Customize the number of sections in the table view.
public override int NumberOfSections (UITableView tableView)
{
return 1;
}
public override int RowsInSection (UITableView tableview, int section)
{
return controller.listSecInfo.Count;
}
public override string TitleForHeader (UITableView tableView, int section)
{
return "Securities";
}
// Customize the appearance of table view cells.
public override UITableViewCell GetCell (UITableView tableView, MonoTouch.Foundation.NSIndexPath indexPath)
{
string cellIdentifier = "Cell";
var cell = tableView.DequeueReusableCell (cellIdentifier);
if (cell == null) {
cell = new UITableViewCell (UITableViewCellStyle.Subtitle, cellIdentifier);
//Add in a detail disclosure icon to each cell
cell.Accessory = UITableViewCellAccessory.DetailDisclosureButton;
}
// Configure the cell.
var sInfo = controller.listSecInfo [indexPath.Row];
cell.TextLabel.Text = String.Format ("{0}",sInfo.SecCode);
cell.DetailTextLabel.Text = sInfo.SecName;
return cell;
}
private void InfoAlert (string msg)
{
using (UIAlertView av = new UIAlertView("Info", msg, null, "OK", null)) {
av.Show ();
}
}
public override void RowSelected (UITableView tableView, NSIndexPath indexPath)
{
var sInfo = controller.listSecInfo [indexPath.Row];
controller.DetailVC.DrawChart(sInfo.SecID, sInfo.SecCode);
}
}
class IndicatorDataSource : UITableViewSource
{
static NSString cellIdentifier = new NSString ("CellId");
RootViewController controller;
public IndicatorDataSource (RootViewController controller)
{
this.controller = controller;
}
// Customize the number of sections in the table view.
public override int NumberOfSections (UITableView tableView)
{
return 1;
}
public override int RowsInSection (UITableView tableview, int section)
{
return controller.listIndicator.Count;
}
public override string TitleForHeader (UITableView tableView, int section)
{
return "Indicators";
}
// Customize the appearance of table view cells.
public override UITableViewCell GetCell (UITableView tableView, MonoTouch.Foundation.NSIndexPath indexPath)
{
string cellIdentifier = "Cell";
var cell = tableView.DequeueReusableCell (cellIdentifier);
if (cell == null) {
cell = new UITableViewCell (UITableViewCellStyle.Subtitle, cellIdentifier);
//Add in a detail disclosure icon to each cell
cell.Accessory = UITableViewCellAccessory.DetailDisclosureButton;
}
// Configure the cell.
var sInfo = controller.listIndicator [indexPath.Row];
cell.TextLabel.Text = String.Format ("{0}",sInfo.DescriptiveName);
cell.DetailTextLabel.Text = sInfo.ShortName;
return cell;
}
private void InfoAlert (string msg)
{
using (UIAlertView av = new UIAlertView("Info", msg, null, "OK", null)) {
av.Show ();
}
}
public override void RowSelected (UITableView tableView, NSIndexPath indexPath)
{
var sInfo = controller.listIndicator [indexPath.Row];
//controller.DetailVC.DrawChart(sInfo.SecID, sInfo.SecCode);
}
}
}
However, it crashes when I click the second tab. I am getting the error as below
"Got a SIGSEGV while executing native code"
The first list populated ok.
I think the UITableViewController objects are getting collected and causing your abort. Make secController and secController member variables.
public partial class RootViewController : UITabBarController
{
UITableViewController secController;
UITableViewController IndiController;
public DetailViewController DetailVC { get; set; }
...
public override void ViewDidLoad ()
{
base.ViewDidLoad ();
//Read data from Database..
secController = new UITableViewController ();
IndiController = new UITableViewController ();
Related
I have Tableview with longpress cell.
I can't read the data inside the cell which have been long pressed.
rowselected() method is not the right way because I must select cell first. I didn't want to select cell first.
This is my table adapter class:
internal class AbsetAdapterClass : UITableViewSource
{
private List<benood2.AbsentClass> absentList;
public AbsetAdapterClass(List<benood2.AbsentClass> absentList)
{
this.absentList = absentList;
}
public override UITableViewCell GetCell(UITableView tableView, NSIndexPath indexPath)
{
var cell = (TableClass)tableView.DequeueReusableCell("cell_id", indexPath);
var AbsentDay = absentList[indexPath.Row];
var longPressGesture = new UILongPressGestureRecognizer(LongPressMethod);
cell.AddGestureRecognizer(longPressGesture);
cell.UpdateCell(AbsentDay);
return cell;
}
public override nint RowsInSection(UITableView tableview, nint section)
{
return absentList.Count;
}
public override void RowSelected(UITableView tableView, NSIndexPath indexPath)
{
PublicClass.ReadCellValue = "";
var GetCellValue = absentList[indexPath.Row].BandValue;
tableView.DeselectRow(indexPath, true);
}
void LongPressMethod(UILongPressGestureRecognizer gestureRecognizer)
{
if (gestureRecognizer.State == UIGestureRecognizerState.Began)
{
Toast.MakeToast("I want to read the cell data ").SetTitle(PublicClass.ReadCellID.ToString()).SetDuration(ToastDuration.Regular).Show();
}
}
}
I can't get the long press cell data
You could attach LongPressGesture to the UITableView instead of the UITableViewCell.
You could try the following code (Note: i made my demo based on the Xamarin.iOS official samples):
public override void ViewDidLoad ()
{
base.ViewDidLoad ();
table = new UITableView(new CGRect(0, 0, width, height));
...
// add longPressGesture to the tableView
var longPressGesture = new UILongPressGestureRecognizer(LongPressMethod);
table.AddGestureRecognizer(longPressGesture);
...
}
Then for LongPressMethod:
void LongPressMethod(UILongPressGestureRecognizer gestureRecognizer)
{
var p = gestureRecognizer.LocationInView(table);
var indexPath = table.IndexPathForRowAtPoint(p);
if (indexPath == null)
{
Console.WriteLine("Long press on table view but not on a row.");
}
else if (gestureRecognizer.State == UIGestureRecognizerState.Began)
{
Console.WriteLine("Long press on {0} row", indexPath.Row);
//you could get the selectedItem through the Row index
}
}
For more info, you could refer to Working with Tables and Cells in Xamarin.iOS.
Hope it works for you.
Here is a scenario that I am encountering. I am having a login screen with UserName as one of the fields. The user can select a user using a dropdown list (implemented via a button - to simulate drop down arrow, a popover controller and a table view). I having a controller (UserNameController) which has the logic of fetching the usernames and binding the same to the table view within it. The UserNameController is called via ViewController.cs which has the textfield and the dropdown button using below code:
var content = this.Storyboard.InstantiateViewController("UserNameLookUp") as UserNameController;
UIPopoverController popover = new UIPopoverController(content);
//popover.SetPopoverContentSize(new SizeF(80, 80), true);
popover.PresentFromRect(new RectangleF(float.Parse((sender.Frame.X + 115).ToString()),
float.Parse((sender.Frame.Y + 180).ToString())
, 80, 80), View, UIPopoverArrowDirection.Up, true);
and in UserNameController:
public override void ViewDidLoad()
{
string[] userName = new string[10];
tblVwUserName.Source = new TableSource(userName);
}
}
and TabelSource.cs looks like this:
public class TableSource : UITableViewSource
{
string[] TableItems;
string CellIdentifier = "TableCell";
public TableSource(string[] items)
{
TableItems = items;
}
public override nint RowsInSection(UITableView tableview, nint section)
{
return TableItems.Length;
}
public override UITableViewCell GetCell(UITableView tableView, NSIndexPath indexPath)
{
UITableViewCell cell = tableView.DequeueReusableCell(CellIdentifier);
string item = TableItems[indexPath.Row];
//---- if there are no cells to reuse, create a new one
if (cell == null)
{ cell = new UITableViewCell(UITableViewCellStyle.Default, CellIdentifier); }
cell.TextLabel.Text = item;
return cell;
}
public override void RowSelected(UITableView tableView, NSIndexPath indexPath)
{
// HOW TO SET BACK THE USERNAME TEXT FIELD IN VIEWCONTROLLER? AND CLOSE THE POPUP
tableView.DeselectRow(indexPath, true);
}
}
Now how do i need to display the selected username in the viewcontroller's textfield and close the popup?
Thanks!
Sid
I typically solve this requirement with properties on the TableViewSource and the TableViewController. Your source will change to:
public class TableSource : UITableViewSource
{
string[] TableItems;
string CellIdentifier = "TableCell";
public string SelectedItem {get; set;}
public TableSource(string[] items)
{
TableItems = items;
}
public override nint RowsInSection(UITableView tableview, nint section)
{
return TableItems.Length;
}
public override UITableViewCell GetCell(UITableView tableView, NSIndexPath indexPath)
{
UITableViewCell cell = tableView.DequeueReusableCell(CellIdentifier);
string item = TableItems[indexPath.Row];
//---- if there are no cells to reuse, create a new one
if (cell == null)
{ cell = new UITableViewCell(UITableViewCellStyle.Default, CellIdentifier); }
cell.TextLabel.Text = item;
return cell;
}
public override void RowSelected(UITableView tableView, NSIndexPath indexPath)
{
SelectedItem = items[indexPath.Row];
tableView.DeselectRow(indexPath, true);
}
}
Now you need a way to get that value. There are two possible ways:
1) UserNameController is of type UITableViewController, than it would be (content.TableView.Source as TableSource).SelectedItem
2) UserNameController is not of type UITableViewController, than I would add a property too that returns the property of the TableViewSource.
Last thing to do is closing the Popover and query the selected item. For this task I would wrap the UserNameController in a UINavigationController and add a Cancel and a Done button into it like this:
var navigationController = new UINavigationController(content);
var popover = new UIPopoverController(navigationController);
content.NavigationItem.SetLeftBarButtonItem(new UIBarButtonItem(UIBarButtonSystemItem.Cancel, (s, e) =>
{
parentController.DismissViewController(true, null);
}), true);
content.NavigationItem.SetRightBarButtonItem(new UIBarButtonItem(UIBarButtonSystemItem.Done, (s, e) =>
{
parentController.DismissViewController(true, null);
var selectedItem = (content.Source as TableSource).SelectedItem;
}), true);
I've decided to delete the button, and now want to navigate. The idea is simple; I want to, when I click ''Next Site'' be transfered to another site in the application. However I don't know how to do this.
Code:
using System;
using System.Collections.Generic;
using System.Text;
using Foundation;
using UIKit;
namespace TableView
{
public class TableSource : UITableViewSource
{
string[] tableItems;
string cellIdentifier = "TableCell";
public TableSource (string[] items)
{
tableItems = items;
}
public override nint RowsInSection(UITableView tableview, nint section)
{
return tableItems.Length;
}
public override void RowSelected(UITableView tableView, NSIndexPath indexPath)
{
new UIAlertView("Alert", "You selected: " + tableItems[indexPath.Row], null, "Next Site", null).Show();
tableView.DeselectRow(indexPath, true);
}
public override UITableViewCell GetCell(UITableView tableView, NSIndexPath indexPath)
{
UITableViewCell cell = tableView.DequeueReusableCell(cellIdentifier);
if (cell == null)
cell = new UITableViewCell(UITableViewCellStyle.Subtitle, cellIdentifier);
cell.TextLabel.Text = tableItems[indexPath.Row];
if(indexPath.Row > -1)
cell.DetailTextLabel.Text = tableItems[indexPath.Row - 0];
return cell;
}
}
}
UIAlertView is depricated since iOS 8 and should be replaced with UIAlertController. For an UIAlertController you can provide actions.
var alert = UIAlertController.Create("Title", "Message", UIAlertControllerStyle.Alert);
alert.AddAction(UIAlertAction.Create("Ok", UIAlertActionStyle.Default, ActionHandler));
Inside your ActionHandler you can switch to your new page.
I want to use UITableView on XamarinApp.
I tried UITableView example Populating a Table with Data ,but it doesn't work.
When i used this.Add(table); cause crash. When I remove this.Add(table) it's shows empty table.
Please help me...
Here is my code
using Foundation;
using System;
using System.CodeDom.Compiler;
using UIKit;
namespace KUkyuko
{
partial class MyTableViewSource : UITableView
{
public MyTableViewSource(IntPtr handle) : base (handle)
{
var table = this;
string[] tableItems = new string[] {"Vegetables","Fruits","Flower Buds","Legumes","Bulbs","Tubers"};
table.Source = new TableSource(tableItems);
this.Add(table); //this code cause crash
}
}
public class TableSource : UITableViewSource {
string[] TableItems;
string CellIdentifier = "TableCell";
public TableSource (string[] items)
{
TableItems = items;
}
public override nint RowsInSection (UITableView tableview, nint section)
{
return TableItems.Length;
}
public override UITableViewCell GetCell (UITableView tableView, NSIndexPath indexPath)
{
UITableViewCell cell = tableView.DequeueReusableCell (CellIdentifier);
string item = TableItems[indexPath.Row];
//---- if there are no cells to reuse, create a new one
if (cell == null)
{ cell = new UITableViewCell (UITableViewCellStyle.Default, CellIdentifier); }
cell.TextLabel.Text = item;
return cell;
}
}
}
Im abit unsure as to what you trying to achieve but
I would change the tableview to a tableViewController like so::
partial class TableViewController : UITableViewController
{
public TableViewController (IntPtr handle) : base (handle)
{
// Register the TableView's data source
string[] tableItems = new string[] {"Vegetables","Fruits","Flower Buds","Legumes","Bulbs","Tubers"};
this.TableView.Source = new TableSource(tableItems);
}
}
public class TableSource : UITableViewSource {
string[] TableItems;
string CellIdentifier = "TableCell";
public TableSource (string[] items)
{
TableItems = items;
}
public override nint RowsInSection (UITableView tableview, nint section)
{
return TableItems.Length;
}
public override nint NumberOfSections (UITableView tableView)
{
// TODO: return the actual number of sections
return 1;
}
public override UITableViewCell GetCell (UITableView tableView, NSIndexPath indexPath)
{
UITableViewCell cell = tableView.DequeueReusableCell (CellIdentifier);
string item = TableItems[indexPath.Row];
//---- if there are no cells to reuse, create a new one
if (cell == null)
{ cell = new UITableViewCell (UITableViewCellStyle.Default, CellIdentifier); }
cell.TextLabel.Text = item;
return cell;
}
}
If you are using the table inside a viewController then you need to do this part in your viewController and set up a outlet for the table.
The reason this code crashes as you are adding this to this:
var table = this;
string[] tableItems = new string[] {"Vegetables","Fruits","Flower Buds","Legumes","Bulbs","Tubers"};
table.Source = new TableSource(tableItems);
this.Add(table); //this code cause crash as it is the same as this.Add(this)
Hope this helps!
I'm an absolute beginner at iOS.
I want to provide swipe-left actions on a table but even though i am setting a proper delegate subclass the EditActionsForRow method is never called on it.
Here's my code:
using System;
using UIKit;
using Foundation;
using System.Linq;
using System.Diagnostics;
namespace Tasky {
public partial class TaskyViewController : UIViewController {
TasksRepository tasksRepository;
TaskItemViewSource tasksViewSource;
public TaskyViewController (IntPtr handle) : base (handle) {
tasksRepository = new TasksRepository ();
tasksViewSource = new TaskItemViewSource ();
tasksViewSource.Data = new TaskItem[0];
tasksViewSource.DeleteClicked += HandleTaskDeleteClicked;
}
public override void ViewDidLoad () {
base.ViewDidLoad ();
TasksTable.Delegate = tasksViewSource;
TasksTable.Source = tasksViewSource;
}
public async override void ViewDidAppear (bool animated) {
base.ViewDidAppear (animated);
var tasks = await tasksRepository.GetAllTasksAsync ();
tasksViewSource.Data = tasks.ToArray ();
TasksTable.ReloadData ();
}
async void HandleTaskDeleteClicked (object sender, NSIndexPath e) {
await tasksRepository.DeleteTaskAsync (tasksViewSource.Data [e.Row]);
TasksTable.ReloadData ();
}
}
public class TaskItemViewSource : UITableViewSource, IUITableViewDelegate {
public TaskItem[] Data { get; set; }
public override UITableViewCell GetCell (UITableView tableView, NSIndexPath indexPath) {
var task = Data [indexPath.Row];
UITableViewCellStyle cellStyle;
if (String.IsNullOrEmpty (task.Description)) {
cellStyle = UITableViewCellStyle.Default;
} else {
cellStyle = UITableViewCellStyle.Subtitle;
}
var taskCell = new UITableViewCell (cellStyle, "TaskCell");
taskCell.TextLabel.Text = Data [indexPath.Row].Title;
if (!String.IsNullOrEmpty (task.Description)) {
taskCell.DetailTextLabel.Text = Data [indexPath.Row].Description;
}
return taskCell;
}
public override nint RowsInSection (UITableView tableView, nint section) {
return Data.Length;
}
public override void RowSelected (UITableView tableView, NSIndexPath indexPath) {
Debug.WriteLine ("Deselected row #" + indexPath.Row);
tableView.DeselectRow (indexPath, true);
}
public event EventHandler<NSIndexPath> DeleteClicked;
public override UITableViewRowAction[] EditActionsForRow (UITableView tableView, NSIndexPath indexPath) {
Debug.WriteLine ("Inflating edit actions...");
var deleteButton = UITableViewRowAction.Create (
UITableViewRowActionStyle.Destructive,
"Delete",
(action, index) => {
if (DeleteClicked != null) {
DeleteClicked (this, index);
}
});
return new [] { deleteButton };
}
}
}
EDIT:
I managed to fuse the delegate and the view source with Jason's remark, deselecting is now working fine.
Xamarin's TableSource combines two native iOS concepts, the DataSource and the Delegate. Xamarin also provides mappings to the DataSource and Delegate classes. However, you should not mix TableSource with DataSource and Delegate.
From Xamarin's TableView docs:
If you are looking at Objective-C code or documentation, be aware that
Xamarin.iOS aggregates the UITableViewDelegate protocol and
UITableViewDataSource class into this one class. There is no
comparable UITableViewSource class or protocol in Objective-C.