I Have the following viewcontroller with a tableview and a custom cell:
using System;
using System.Drawing;
using MonoTouch.Foundation;
using MonoTouch.UIKit;
using System.Linq;
using System.Threading;
using System.Data;
using System.IO;
using Mono.Data.Sqlite;
using System.Collections.Generic;
using Zurfers.Mobile.Core;
using AlexTouch.MBProgressHUD;
using System.Collections;
namespace Zurfers.Mobile.iOS
{
public partial class iPhoneHotelSearchViewController : UIViewController
{
MBProgressHUD hud;
public string Destination {
get;
set;
}
public DateTime CheckInDate {
get;
set;
}
public DateTime CheckOutDate {
get;
set;
}
public int Rooms {
get;
set;
}
public iPhoneHotelSearchViewController (IntPtr handle) : base (handle)
{
}
public override void ViewDidLoad ()
{
base.ViewDidLoad ();
hud = new MBProgressHUD(this.View);
hud.Mode = MBProgressHUDMode.Indeterminate;
hud.LabelText = "Loading...";
hud.DetailsLabelText = "Searching Hotel";
this.View.AddSubview(hud);
hud.Show(true);
}
public override void ViewDidAppear (bool animated) {
base.ViewDidAppear (animated);
SearchHotel ();
}
public void SearchHotel (){
Hotel hotel = new Hotel();
var distribution = new HotelDistribution[]{new HotelDistribution(){ Adults = 1, Children = 0, ChildrenAges = new int[0]} };
var items = hotel.SearchHotels(Convert.ToDateTime("2013-08-08"),Convert.ToDateTime("2013-09-09 "),"(MIA)", distribution,"","","",0);
List<DtoHotelinformation> data = new List<DtoHotelinformation>();
foreach (var item in items)
{
DtoHotelinformation DtoHotelinformation = new DtoHotelinformation();
DtoHotelinformation.code = item.Code.ToString();
DtoHotelinformation.price = item.Price.ToString();
DtoHotelinformation.title = item.Name.ToString().ToTitleCase();
DtoHotelinformation.subtitle = item.Address.ToString();
DtoHotelinformation.rating = item.Rating.ToString();
DtoHotelinformation.imageUlr = item.ImageUrl;
data.Add(DtoHotelinformation);
}
hud.Hide(true);
hud.RemoveFromSuperview();
HotelSearchTable.Source = new HotelTableSource(data.ToArray());
HotelSearchTable.ReloadData();
}
partial void GoBack (MonoTouch.Foundation.NSObject sender)
{
DismissViewController(true, null);
}
}
}
Now the table source
using System;
using MonoTouch.Foundation;
using MonoTouch.UIKit;
namespace Zurfers.Mobile.iOS
{
public class HotelTableSource : UITableViewSource
{
DtoHotelinformation[] tableItems;
NSString cellIdentifier = new NSString("TableCell");
public HotelTableSource (DtoHotelinformation[] items)
{
tableItems = items;
}
public override int RowsInSection (UITableView tableview, int section)
{
return tableItems.Length;
}
public override void RowSelected (UITableView tableView, NSIndexPath indexPath)
{
//WHAT TO DO HERE
tableView.DeselectRow (indexPath, true); // normal iOS behaviour is to remove the blue highlight
}
public override UITableViewCell GetCell (UITableView tableView, MonoTouch.Foundation.NSIndexPath indexPath)
{
CustomCell cell = tableView.DequeueReusableCell(cellIdentifier) as CustomCell;
if (cell == null)
cell = new CustomCell(cellIdentifier);
cell.UpdateCell(tableItems[indexPath.Row].title, tableItems[indexPath.Row].subtitle, tableItems[indexPath.Row].price,
tableItems[indexPath.Row].imageUlr, tableItems[indexPath.Row].rating );
return cell;
}
public override float GetHeightForRow(UITableView tableView, NSIndexPath indexPath)
{
return 70;
}
}
}
Finally the customcell code:
using System;
using System.Drawing;
using MonoTouch.Foundation;
using MonoTouch.UIKit;
using MonoTouch.Dialog.Utilities;
namespace Zurfers.Mobile.iOS
{
public class CustomCell : UITableViewCell, IImageUpdated
{
UILabel headingLabel, subheadingLabel, priceLabel;
UIImageView imageService;
UIImageView star, star2, star3, star4, star5;
public CustomCell (NSString cellId) : base (UITableViewCellStyle.Default, cellId)
{
imageService = new UIImageView();
star = new UIImageView();
star2 = new UIImageView();
star3 = new UIImageView();
star4 = new UIImageView();
star5 = new UIImageView();
headingLabel = new UILabel(){
Font = UIFont.FromName("Verdana-Bold", 14f),
BackgroundColor = UIColor.Clear,
TextColor = UIColor.FromRGB(241, 241, 211)
};
subheadingLabel = new UILabel(){
Font = UIFont.FromName("Verdana-Bold", 8f),
TextColor = UIColor.FromRGB(255, 255, 255),
BackgroundColor = UIColor.Clear
};
priceLabel = new UILabel(){
Font = UIFont.FromName("Verdana", 14f),
TextColor = UIColor.FromRGB(241, 241, 211),
BackgroundColor = UIColor.Clear
};
AddSubview(imageService);
AddSubview(headingLabel);
AddSubview(subheadingLabel);
AddSubview(priceLabel);
AddSubview(star);
AddSubview(star2);
AddSubview(star3);
AddSubview(star4);
AddSubview(star5);
}
public void UpdateCell (string title, string subtitle, string price, string imageUlr, string rating )
{
if (imageUlr != null) {
var u = new Uri(imageUlr);
ImageLoader MyLoader= new ImageLoader(50,50);
imageService.Image = MyLoader.RequestImage(u,this);
} else {
imageService.Image = UIImage.FromFile("generic_no_image_tiny.jpg");
}
headingLabel.Text = title;
subheadingLabel.Text = subtitle;
if (subtitle.Length > 40) {
subheadingLabel.LineBreakMode = UILineBreakMode.WordWrap;
subheadingLabel.Lines = 0;
}
switch (rating) {
case "T":
star.Image = UIImage.FromFile("ZurfersMovil-Stars.png");
star2.Image = UIImage.FromFile("ZurfersMovil-Stars.png");
break;
case "S":
star.Image = UIImage.FromFile("ZurfersMovil-Stars.png");
star2.Image = UIImage.FromFile("ZurfersMovil-Stars.png");
star3.Image = UIImage.FromFile("ZurfersMovil-Stars.png");
break;
case "F":
star.Image = UIImage.FromFile("ZurfersMovil-Stars.png");
star2.Image = UIImage.FromFile("ZurfersMovil-Stars.png");
star3.Image = UIImage.FromFile("ZurfersMovil-Stars.png");
star4.Image = UIImage.FromFile("ZurfersMovil-Stars.png");
break;
case "L":
star.Image = UIImage.FromFile("ZurfersMovil-Stars.png");
star2.Image = UIImage.FromFile("ZurfersMovil-Stars.png");
star3.Image = UIImage.FromFile("ZurfersMovil-Stars.png");
star4.Image = UIImage.FromFile("ZurfersMovil-Stars.png");
star5.Image = UIImage.FromFile("ZurfersMovil-Stars.png");
break;
}
priceLabel.Text = "USD " + price;
priceLabel.Font = UIFont.BoldSystemFontOfSize (16);
}
public void UpdatedImage (Uri uri)
{
imageService.Image = ImageLoader.DefaultRequestImage(uri, this);
}
public override void LayoutSubviews ()
{
base.LayoutSubviews ();
imageService.Frame = new RectangleF(10, 10, 50, 33);
headingLabel.Frame = new RectangleF(70, 4, 240, 25);
subheadingLabel.Frame = new RectangleF(70, 25, 240, 20);
priceLabel.Frame = new RectangleF(220, 45, 100, 20);
star.Frame = new RectangleF(70, 45, 15, 15);
star2.Frame = new RectangleF(85, 45, 15, 15);
star3.Frame = new RectangleF(100, 45, 15, 15);
star4.Frame = new RectangleF(115, 45, 15, 15);
star5.Frame = new RectangleF(130, 45, 15, 15);
}
}
}
I want to open another viewcontroller (iPhoneHotelDetailViewController) when the user touch a cell of the table view. But I don not have any idea of how to do this.
Could you help me please.
Thanks in advance for your help.
Generally, you want a NavigationController to be the "top" element in your app, wrapping all the other controllers.
In your AppDelegate, create a NavigationController, and make it the root of your application.
Then create an instance of your Search controller and push it onto the NavigationController.
Finally, add a NavigationController property to the constructor of your TableSource.
NavigationController nav;
public HotelTableSource (DtoHotelinformation[] items, NavigationController nav)
{
this.nav = nav;
tableItems = items;
}
When you create your TableSource, pass the NavigationController reference in. You can do this because all ViewControllers have a property that points to their NavigationController, if they are contained within one.
HotelSearchTable.Source = new HotelTableSource(data.ToArray(), this.NavigationController);
Finally, in your RowSelected, create an instance of the new ViewController you want to display:
public override void RowSelected (UITableView tableView, NSIndexPath indexPath)
{
//WHAT TO DO HERE
MyDetailController myDetail = new MyDetailController();
nav.PushViewController(myDetail, true);
tableView.DeselectRow (indexPath, true); // normal iOS behaviour is to remove the blue highlight
}
I think that link to UINavigationController (UI component) in UITableViewSource is a bit weird. I recommend to use event-based approach:
Declare event in UITableViewSource and call it on row selection:
public event Action<int> OnRowSelect;
...
public override void RowSelected (UITableView tableView, NSIndexPath indexPath)
{
tableView.DeselectRow (indexPath, true); // normal iOS behaviour is to remove the blue highlight
if (OnRowSelect != null) {
OnRowSelect(indexPath.Row);
}
}
Then, handle event on UIViewController - push new UIViewController:
var source = data.ToArray();
source.OnRowSelect += HandleOnRowSelect;
HotelSearchTable.Source = new HotelTableSource();
HotelSearchTable.ReloadData();
...
void HandleOnRowSelect(int index)
{
var data = items[index];
// Pass data to new view controller and push it
}
Tip to avoid memory leaks: don't forget to unsubscribe from OnRowSelect when you Pop this UIViewController or making new UITableViewSource instance. I.e:
Declare source in as class member;
Unsubscribe from it's event in, for example, ViewWillDisappear:
source.OnRowSelect -= HandleOnRowSelect;
If you are using StoryBord there is a very easy way to do this. You would then pass the data whit in the PrepareForSegue method like this.
public override void PrepareForSegue (UIStoryboardSegue segue, NSObject sender)
{
base.PrepareForSegue (segue, sender);
NSIndexPath indexPatch = tableView.IndexPathForSelectedRow;
if (segue.Identifier.Equals ("showHotelDetail")) {
var vc = segue.DestinationViewController as iPhoneHotelDetailViewController;
if (vc != null) {
//Pass some date to the iPhoneHotelDetailViewController if needed.
vc.hotelName = this.tableItems [indexPatch.Row].hotelName;
}
}
}
In your StoryBoard connect the customCell with the iPhoneHotelDetailViewController and call the segue "showHotelDetail" for example.
Related
I am making custom cell in xamarin iOS. In the cell I have two Button which is display in the below figure.
Figure :
Two Button are :
Create Appointment
View Detail
I want to create this two different Button click Event in My Source class so that I can send data to different ViewController for my purpose.
Code :
TableCell class :
public partial class CaseHistoryTableCell : UITableViewCell
{
public static readonly NSString Key = new NSString("CaseHistoryTableCell");
public static readonly UINib Nib;
static CaseHistoryTableCell()
{
Nib = UINib.FromName("CaseHistoryTableCell", NSBundle.MainBundle);
}
public CaseHistoryTableCell(IntPtr handle) : base(handle)
{
// Note: this .ctor should not contain any initialization logic.
}
public static CaseHistoryTableCell Create()
{
return (CaseHistoryTableCell)Nib.Instantiate(null, null)[0];
}
public void BindData(string hospitalLabel, string addressLabel, string drLabel, string patientLabel)
{
this.lbl_hospitalName.Text = hospitalLabel;
this.lbl_address.Text = addressLabel;
this.lbl_drName.Text = drLabel;
this.lbl_patientName.Text = patientLabel;
this.lbl_address.TextColor = UIColor.Clear.FromHexString("#000000", 0.54f);
this.lbl_patientName.TextColor = UIColor.Clear.FromHexString("#000000", 0.54f);
this.lbl_caseDate.TextColor = UIColor.Clear.FromHexString("#000000", 0.54f);
this.lbl_scheDate.TextColor = UIColor.Clear.FromHexString("#000000", 0.54f);
this.lbl_hospitalName.TextColor = UIColor.Clear.FromHexString("#000000", 0.87f);
this.lbl_drName.TextColor = UIColor.Clear.FromHexString("#000000", 0.87f);
this.btn_createAppointment.SetTitleColor(UIColor.Clear.FromHexString("#0072BA", 1.0f), UIControlState.Normal);
this.btn_viewDetail.SetTitleColor(UIColor.Clear.FromHexString("#0072BA", 1.0f), UIControlState.Normal);
}
public override CGRect Frame
{
get
{
return base.Frame;
}
set
{
value.Y += 4;
value.Height -= 2 * 4;
base.Frame = value;
}
}
}
Source Class :
public class CaseHistorySourceClass : UITableViewSource
{
private List<CaseSearchItem> caseSearchItems;
public CaseSearchItem caseSearchItem;
public static event EventHandler RowClicked;
public CaseHistorySourceClass(List<CaseSearchItem> caseSearchItems)
{
this.caseSearchItems = caseSearchItems;
}
public override UITableViewCell GetCell(UITableView tableView, NSIndexPath indexPath)
{
CaseHistoryTableCell cell = tableView.DequeueReusableCell(CaseHistoryTableCell.Key) as CaseHistoryTableCell ?? CaseHistoryTableCell.Create();
var item = caseSearchItems[indexPath.Row];
cell.BindData(item.Organization, item.Address, item.Doctor, item.UserName);
cell.Layer.MasksToBounds = false;
cell.Layer.CornerRadius = 10.0f;
cell.BackgroundColor = UIColor.White;
cell.SetNeedsLayout();
cell.LayoutIfNeeded();
return cell;
}
public override nint RowsInSection(UITableView tableview, nint section)
{
return caseSearchItems.Count;
}
}
My Question :
It is possible to Create two different Button click event in a single Cell.
If yes then How ?
and If No then what is alternative to Perform this type of operation.
Note : I doesn't want to require RowSelected. I only require how to
perform this two different Button click Event.
Don't do such operation on RowSelected
Setting Target with selector will help you out .
public override UITableViewCell GetCell(UITableView tableView, NSIndexPath indexPath)
{
CaseHistoryTableCell cell = tableView.DequeueReusableCell(CaseHistoryTableCell.Key) as CaseHistoryTableCell ?? CaseHistoryTableCell.Create();
var item = caseSearchItems[indexPath.Row];
// setTag to button to identify in which row button is pressed
cell.btnCreateAppointment.tag=indexPath.Row;
cell.btnViewDetail.tag=indexPath.row;
// set Target to a method
cell.btnCreateAppointment.TouchUpInside += createAppointment;
ell.btnViewDetail.TouchUpInside +=viewDetail;
}
These Method will be called when Press you button
public void createAppointment(object sender, EventArgs e)
{
var row=sender.tag;
}
Second button Clicked event
public void viewDetail(object sender, EventArgs e)
{
var row=sender.tag;
}
i hope this work.
You can do this by adding target action to button from your GetCell method:
first add following in your cell class to make buttons accessible:
public UIButton btnCreateAppointment {
get
{
return this.btn_createAppointment;
}
}
public UIButton btnViewDetail
{
get
{
return this.btn_viewDetail;
}
}
Now from modify your GetCell method to add action target
cell.btnCreateAppointment.tag = indexPath.Row;
cell.btnViewDetail.tag = indexPath.row;
//assign action
cell.btnCreateAppointment.TouchUpInside += (sender, e) =>
{
var row = ((UIButton)sender).Tag;
var item = caseSearchItems[row];
};
cell.btnViewDetail.TouchUpInside += (sender, e) =>
{
var row = ((UIButton)sender).Tag;
var item = caseSearchItems[row];
};
I am trying to build an self-sizing UITableView Cell. After googled, I found this tutorial: https://pontifex.azurewebsites.net/self-sizing-uitableviewcell-with-uitextview-in-ios-8/ which is quite good.
In swift, it's saying that tableView?.BeginUpdates can update the size of the custom cell. But It seems not working in xamarin ios.
Could someone help me on that? Many Thanks!
using System;
using Foundation;
using UIKit;
using CoreGraphics;
namespace Ma
{
public partial class DataInput : UITableViewCell
{
public string title { get; set;}
public static readonly UINib Nib = UINib.FromName ("DataInput", NSBundle.MainBundle);
public static readonly NSString Key = new NSString ("DataInput");
public string value { get; set;}
public DataInput (IntPtr handle) : base (handle)
{
}
public static DataInput Create ()
{
return (DataInput)Nib.Instantiate (null, null) [0];
}
public void Populate()
{
this.Title.Text = this.title;
if (!string.IsNullOrEmpty(value)) {
this.Input.Text = this.value;
}
}
public string GetInputValue()
{
return this.Input.Text;
}
public UITableView GetTableView()
{
UITableView table = null;
UIView view = this.Superview;
if (view != null) {
table = (UITableView)view.Superview;
}
return table;
}
public override void AwakeFromNib ()
{
base.AwakeFromNib ();
this.Input.ScrollEnabled = false;
this.Input.Delegate = new DataInputDelegate ();
}
public override void SetSelected (bool selected, bool animated)
{
base.SetSelected (selected, animated);
if (selected) {
this.Input.BecomeFirstResponder ();
} else {
this.Input.ResignFirstResponder ();
}
}
}
public partial class DataInputDelegate : UITextViewDelegate
{
public override void Changed (UITextView textView)
{
var size = textView.Bounds.Size;
var newSize = textView.SizeThatFits (new CGSize (size.Width, size.Height));
if (size.Height != newSize.Height) {
UITextView.AnimationsEnabled = false;
UITableViewCell input = (UITableViewCell)textView.Superview.Superview;
UITableView tableView = (UITableView)input.Superview.Superview;
// This is the place of updating custom cell size, but It's not working now.
tableView.BeginUpdates ();
tableView.EndUpdates ();
UITextView.AnimationsEnabled = true;
var thisIndexPath = tableView.IndexPathForCell (input);
tableView.ScrollToRow (thisIndexPath, UITableViewScrollPosition.Bottom, false);
}
}
}
}
BTW, I am using autolayout and set
TableView.EstimatedRowHeight = 50;
TableView.RowHeight = UITableView.AutomaticDimension;
And I have done the following setting as well.
public override nfloat GetHeightForRow(UITableView tableView, NSIndexPath indexPath)
{
if (indexPath.Row == 0) {
return 80.0f;
}
return UITableView.AutomaticDimension;
}
Many thanks if someone can guide me!
Based on constraints placed on view, then autolayout will work. The code works fine after I set up the constraints of each components.
I am trying to make a custom TableView that has big heights, but when i run it i can only access 2 of my 5 rows in the table(in the example i provided)
Here is a screen shot of how i am viewing my table : http://i.imgur.com/1dsPNj5.png
Here is the link to my Table Source : http://pastebin.com/B7U2BEd8
Here is my view controller :
unclass[] lol= new unclass[amount];
for (nint i = 0; i < amount; i++) {
lol [i] = new unclass ();
Console.WriteLine ("item created");
}
UITableView _table;
_table = new UITableView{ Frame = new CoreGraphics.CGRect (0, 30, View.Bounds.Width, 3000),Source= new TableSource(lol) };
_table.SeparatorStyle = UITableViewCellSeparatorStyle.None;
for (nint i = 0; i < amount; i++) {
lol [i].imager = await this.LoadImage (links[i]); //loads image from the net to table
}
View.AddSubview (_table);
}
I really don't understand why this is happening
Your TableSource is not the problem, I tested it with a blank table.
Also as Jason said you will need to change the table's frame height to "View.Bounds.Height - 30" -30 to compensate for your Y position. I created a simple example below that show all 5 cells. So it might be the way that you are adding the table or if there is anything else in the viewController. Are you able to post more of your view controller's code?
using UIKit;
using CoreGraphics;
using System;
using Foundation;
namespace SO_Xam_actvity
{
public class bigTableViewController : UIViewController
{
public override void ViewDidLoad ()
{
base.ViewDidLoad ();
UITableView _table;
_table = new UITableView{ Frame = new CGRect (0, 30, View.Bounds.Width, View.Bounds.Height-30),Source= new TableSource(new [] {1,1,1,1,1}) };
_table.SeparatorStyle = UITableViewCellSeparatorStyle.None;
View.AddSubview (_table);
}
}
public class TableSource : UITableViewSource
{
int[] tableItems;
string cellIdentifier = bigTableViewCell.Key;
public TableSource (int[] items)
{
tableItems = items;
}
public override nint RowsInSection (UITableView tableview, nint section)
{
return tableItems.Length;
}
public override nfloat GetHeightForRow (UITableView tableView, NSIndexPath indexPath)
{
return 200;
}
public override UITableViewCell GetCell (UITableView tableView, NSIndexPath indexPath)
{
var cell = tableView.DequeueReusableCell (cellIdentifier) as bigTableViewCell;
if (cell == null) {
cell = new bigTableViewCell();
}
cell.DetailTextLabel.Text = $"{indexPath.Row}";
return cell;
}
}
public class bigTableViewCell : UITableViewCell
{
public static readonly NSString Key = new NSString ("bigTableViewCell");
public bigTableViewCell () : base (UITableViewCellStyle.Value1, Key)
{
TextLabel.Text = "TextLabel";
}
}
}
Working with a UICollectionView in Xamarin just as I have before but running into a strange problem -- When the view containing the collection loads, I see the cells for a short moment and then they disappear. I double checked the ContentSize of the CollectionView and apparently it's defaulting to 0 width, 0 height but setting it manually doesn't seem to solve the problem. The CollectionView seems to stick around (if I set the background color to black I see a black View in the parent) but the cells are disappearing
Parent View (UIView subclass):
UICollectionViewFlowLayout layout = new UICollectionViewFlowLayout ();
layout.ItemSize = new SizeF (274, 281);
layout.MinimumInteritemSpacing = 3;
layout.ScrollDirection = UICollectionViewScrollDirection.Horizontal;
var haulCollection = new HaulCollectionController(layout);
haulCollection.CollectionView.Frame = new RectangleF (0, cellHeader.Frame.Bottom, cellHeader.Frame.Width, 281);
AddSubview(haulCollection.CollectionView);
UICollectionViewController:
public class HaulCollectionController : UICollectionViewController
{
public HaulCollectionController (UICollectionViewLayout layout) : base (layout)
{
}
public override void ViewDidLoad ()
{
base.ViewDidLoad ();
CollectionView.BackgroundColor = UIColor.Clear;
CollectionView.RegisterClassForCell (typeof(HaulCollectionCell), HaulCollectionCell.Key);
}
public override int NumberOfSections (UICollectionView collectionView)
{
return 1;
}
public override int GetItemsCount (UICollectionView collectionView, int section)
{
return 6;
}
public override UICollectionViewCell GetCell (UICollectionView collectionView, NSIndexPath indexPath)
{
var cell = collectionView.DequeueReusableCell (HaulCollectionCell.Key, indexPath) as HaulCollectionCell;
return cell;
}
public override bool ShouldHighlightItem (UICollectionView collectionView, NSIndexPath indexPath)
{
return false;
}
}
UICollectionViewCell:
public class HaulCollectionCell : UICollectionViewCell
{
public static readonly NSString Key = new NSString ("HaulCollectionCell");
public UILabel Retailer { get; set; }
public UILabel Brand { get; set; }
public UILabel ItemName { get; set; }
[Export ("initWithFrame:")]
public HaulCollectionCell (RectangleF frame) : base (frame)
{
BackgroundColor = UIColor.Cyan;
var infoOverlay = new UIView (new RectangleF(0, Frame.Height-60, Frame.Width, 55)) {
BackgroundColor = UIColor.FromRGBA(255, 255, 255, 153)
};
Retailer = new UILabel (new RectangleF(15,10,100,22)) {
Font = ViewHelpers.GetFont(20, false),
Text = "DICK'S"
};
Brand = new UILabel (new RectangleF(Retailer.IntrinsicContentSize.Width + 10, 10, 100,22)) {
Font = ViewHelpers.GetFont(20, true),
Text = "Nike"
};
ItemName = new UILabel (new RectangleF(15, Brand.Frame.Bottom + 5, 200,30)) {
Font = ViewHelpers.GetFont(26, false),
Text = "Windrunner Tech Fleece"
};
infoOverlay.AddSubviews (Retailer,Brand,ItemName);
ContentView.Add (infoOverlay);
}
}
can't figure out exactly why I can't get the cells to display...
I have the following CustomCell:
using System;
using System.Drawing;
using MonoTouch.Foundation;
using MonoTouch.UIKit;
namespace Zurfers.Mobile.iOS
{
public class CustomCell : UITableViewCell
{
UILabel headingLabel, subheadingLabel, priceLabel;
UIImageView imageService;
UIImageView star, star2, star3, star4, star5;
public CustomCell (NSString cellId) : base (UITableViewCellStyle.Default, cellId)
{
imageService = new UIImageView();
star = new UIImageView();
star2 = new UIImageView();
star3 = new UIImageView();
star4 = new UIImageView();
star5 = new UIImageView();
headingLabel = new UILabel(){
Font = UIFont.FromName("Cochin-BoldItalic", 22f),
TextColor = UIColor.FromRGB (127, 51, 0),
};
subheadingLabel = new UILabel(){
Font = UIFont.FromName("Cochin-BoldItalic", 22f),
TextColor = UIColor.FromRGB (127, 51, 0),
};
priceLabel = new UILabel(){
Font = UIFont.FromName("Cochin-BoldItalic", 22f),
TextColor = UIColor.FromRGB (127, 51, 0),
};
}
public void UpdateCell (string title, string subtitle, string price, UIImage image)
{
imageService.Image = image;
headingLabel.Text = title;
subheadingLabel.Text = subtitle;
priceLabel.Text = price;
}
public override void LayoutSubviews ()
{
base.LayoutSubviews ();
imageService.Frame = new RectangleF(63, 5, 33, 33);
headingLabel.Frame = new RectangleF(5, 4, 63, 25);
subheadingLabel.Frame = new RectangleF(100, 18, 100, 20);
priceLabel.Frame = new RectangleF(250, 18, 100, 20);
}
}
}
And this is my TableSource:
using System;
using MonoTouch.Foundation;
using MonoTouch.UIKit;
namespace Zurfers.Mobile.iOS
{
public class HotelTableSource : UITableViewSource
{
string[] tableItems;
NSString cellIdentifier = new NSString("TableCell");
public HotelTableSource (string[] items)
{
tableItems = items;
}
public override int RowsInSection (UITableView tableview, int section)
{
return tableItems.Length;
}
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
}
public override UITableViewCell GetCell (UITableView tableView, MonoTouch.Foundation.NSIndexPath indexPath)
{
CustomCell cell = tableView.DequeueReusableCell(cellIdentifier) as CustomCell;
if (cell == null)
cell = new CustomCell(cellIdentifier);
cell.UpdateCell(tableItems[indexPath.Row], tableItems[indexPath.Row], tableItems[indexPath.Row],
UIImage.FromFile (tableItems[indexPath.Row]) );
return cell;
}
}
}
But when I run the app the TableView is empty. Each CustomCell has a value before I create the TableView.
What am I doing wrong?
Thanks in advance for your help.
Cell not only should contains controls, they should be placed on it (or on it's ContentView). Call AddSubview for any controls, which you adding to your custom cell:
ImageService = new UIImageView();
AddSubview(ImageService);
If it doesn't help, try to use UITableViewCell's default controls (TextLabel, DetailTextLabel, ImageView) to show some data. If data appears, there is still an issue in your custom UITableViewCell (wrong frames, empty texts), If not, issue is in UITableViewSource (empty data).