Xamarin: UICollection Image reorder Issue - ios

I am using UICollectionView to store images and I can reorder them by overriding CanMove And MoveItem.
But the items inside the UICollection only reorder when cell size is large like if cell size is around 106 height and width, then they can be reordered if they are smaller in size, they are cannot be reordered.
View:
public override void ViewDidLoad()
{
base.ViewDidLoad();
//ImageCv is the name of UiCollectionView
var collectionLayout = new PostImageFlowLayout(3, 0.85f);
var allCollectionSource = new PostImageColectionSource(ImageCv, (ViewModel as NewPostDetailViewModel));
ImageCv.RegisterNibForCell(PostImageCell.Nib, PostImageCell.Key);
ImageCv.RegisterClassForSupplementaryView(typeof(CollectionHeader), UICollectionElementKindSection.Header, new NSString("headerId"));
ImageCv.BackgroundColor = UIColor.Clear;
ImageCv.Hidden = false;
ImageCv.DataSource = allCollectionSource;
ImageCv.Delegate = collectionLayout;
var longPressGesture = new UILongPressGestureRecognizer(gesture =>
{
// Take action based on state
switch (gesture.State)
{
case UIGestureRecognizerState.Began:
var selectedIndexPath = ImageCv.IndexPathForItemAtPoint(gesture.LocationInView(View));
if (selectedIndexPath != null)
ImageCv.BeginInteractiveMovementForItem(selectedIndexPath);
Debug.WriteLine("Gesture Recognition: Activated");
break;
case UIGestureRecognizerState.Changed:
ImageCv.UpdateInteractiveMovement(gesture.LocationInView(View));
Debug.WriteLine("Gesture activated: Item location is changed");
break;
case UIGestureRecognizerState.Ended:
ImageCv.EndInteractiveMovement();
Debug.WriteLine("Gesture activation: complete");
break;
default:
ImageCv.CancelInteractiveMovement();
Debug.WriteLine("Gesture activation: Terminate");
break;
}
});
// Add the custom recognizer to the collection view
ImageCv.AddGestureRecognizer(longPressGesture);
}
UICollectionViewDelegateFlowLayout
using System;
using System.Windows.Input;
using CoreGraphics;
using UIKit;
namespace Sources.CollectionSources
{
public class PostImageFlowLayout : UICollectionViewDelegateFlowLayout
{
private float headerHeight;
private int noOfItems;
private bool isLoading;
public PostImageFlowLayout(int noOfItems, float headerHeight = 0f)
{
this.noOfItems = noOfItems;
this.headerHeight = headerHeight;
}
public override CGSize GetSizeForItem(UICollectionView collectionView, UICollectionViewLayout layout, Foundation.NSIndexPath indexPath)
{
return GetPostCellSize();
}
public override CGSize GetReferenceSizeForHeader(UICollectionView collectionView, UICollectionViewLayout layout, nint section)
{
return new CGSize(collectionView.Frame.Width, headerHeight);
}
public override UIEdgeInsets GetInsetForSection(UICollectionView collectionView, UICollectionViewLayout layout, nint section)
{
return new UIEdgeInsets(0, 0, 0, 0);
}
private CGSize GetPostCellSize()
{
var relativeWidth = (UIScreen.MainScreen.Bounds.Width - 2) / this.noOfItems;
return new CGSize(relativeWidth, relativeWidth);
//return new CGSize(55, 55);
}
}
}
Source
public class PostImageColectionSource : MvxCollectionViewSource
{
private NewPostDetailViewModel newPostDetailViewModel;
private string type;
static NSString animalCellId = new NSString("PostImageCell");
static NSString headerId = new NSString("Header");
List<IAnimal> animals;
protected override NSString DefaultCellIdentifier
{
get
{
return PostImageCell.Key;
}
}
public override System.Collections.IEnumerable ItemsSource
{
get
{
return base.ItemsSource;
}
set
{
base.ItemsSource = value;
CollectionView.ReloadData();
}
}
public PostImageColectionSource(UICollectionView collectionView, NewPostDetailViewModel newPostDetailViewModel) : base(collectionView)
{
this.newPostDetailViewModel = newPostDetailViewModel;
animals = new List<IAnimal>();
for (int i = 0; i < 20; i++)
{
animals.Add(new Monkey(i));
}
}
public override nint NumberOfSections(UICollectionView collectionView)
{
return 1;
}
public override nint GetItemsCount(UICollectionView collectionView, nint section)
{
return 5;// animals.Count;
}
public override UICollectionViewCell GetCell(UICollectionView collectionView, NSIndexPath indexPath)
{
var cell = (PostImageCell)collectionView.DequeueReusableCell(animalCellId, indexPath);
var animal = animals[indexPath.Row];
cell.Result(indexPath.Row);
return cell;
}
public override bool CanMoveItem(UICollectionView collectionView, NSIndexPath indexPath)
{
Debug.WriteLine("Ready to move images");
//System.Diagnostics.Debug.WriteLine("Checking if it can move the item");
return true;
}
public override void MoveItem(UICollectionView collectionView, NSIndexPath sourceIndexPath, NSIndexPath destinationIndexPath)
{
//base.MoveItem(collectionView, sourceIndexPath, destinationIndexPath);
Debug.WriteLine("Start moving images to reorder");
var item = animals[(int)sourceIndexPath.Item];
animals.RemoveAt((int)sourceIndexPath.Item);
animals.Insert((int)destinationIndexPath.Item, item);
}
}
When the GetPostCellSize in PostImageFlowLayout has width and height of around 100, the CanMove and MoveItem in PostImageColectionSource are being called and items are being reordered. But if the GetPostCellSize has width and height of around 50 or 70, even though the gestures are activated, CanMove and MoveItem in PostImageColectionSource are not being called hence cannot be moved.
Can anyone hope me with reordering the images in UICollectionView when the cell size is small like around width and height of 70.
Thank you.
I am tagging swift and objective-C as this issue is related to IOS in general and not xamarin specific

Main issue here is that you need to pass in the collection view to the gesture.LocationInView(View) call instead of the main View. In ViewDidLoad in the UILongPressGestureRecognizer change:
var selectedIndexPath = ImageCv.IndexPathForItemAtPoint(gesture.LocationInView(View));
and
ImageCv.UpdateInteractiveMovement(gesture.LocationInView(View));
to
var selectedIndexPath = ImageCv.IndexPathForItemAtPoint(gesture.LocationInView(ImageCv)); // <-- pass in ImageCV instead of View. (where ImageCV is the collection view)
and
ImageCv.UpdateInteractiveMovement(gesture.LocationInView(ImageCv)); // <-- pass in ImageCV instead of View.
Another thing to note, but not a huge deal, is that PostImageColectionSource is ultimately derived from UICollectionViewSource, which is a combo of UICollectionViewDelegate and UICollectionViewDataSource in one class, but is being assigned to the DataSource property of the collection view. All this means is that though you can implement methods for UICollectionViewDelegate in PostImageColectionSource the delegate methods will not be called on that class since the Delegate property of the collection view is set to the PostImageFlowLayout, which derives ultimately from UICollectionViewDelegate via UICollectionViewDelegateFlowLayout.

Related

Two Button click event in single cell in TableView in iOS(Xamarin)

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];
};

Xamarin ios how to make a self-sizing UITableViewCell while editing

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.

GetViewForSupplementaryElement not getting called when trying to show heading in UICollectionView

I am trying to setup a UICollectionView within my existing UIViewController. Everything is working except for getting a title to show for each section - I can't figure out what I'm doing wrong.
My code in the UIViewController to initiate the collection view:
public partial class ViewController : UIViewController
{
//...
public override void ViewDidLoad ()
{
base.ViewDidLoad ();
CollectionView_Outlet.RegisterClassForCell(typeof(ModifierCell), ModifierCell.CellID);
CollectionView_Outlet.RegisterClassForSupplementaryView (typeof(Header), UICollectionElementKindSection.Header, Header.HeaderId);
CollectionView_Outlet.ShowsHorizontalScrollIndicator = false;
CollectionView_Outlet.Source = new ModifiersSource(this);
CollectionView_Outlet.BackgroundColor = UIColor.White;
CollectionView_Outlet.ReloadData();
}
//...
}
Then I have created a subclass of UICollectionViewSource:
public class ModifiersSource : UICollectionViewSource
{
ViewController senderVC;
public ModifiersSource(ViewController sender)
{
senderVC = sender;
}
public override nint NumberOfSections(UICollectionView collectionView)
{
return 2;
}
public override nint GetItemsCount (UICollectionView collectionView, nint section)
{
return senderVC.modifiers.Count;
}
public override UICollectionViewCell GetCell(UICollectionView collectionView, NSIndexPath indexPath)
{
//...
}
public override UICollectionReusableView GetViewForSupplementaryElement(UICollectionView collectionView, NSString elementKind, NSIndexPath indexPath)
{
var headerView = (Header)collectionView.DequeueReusableSupplementaryView (elementKind, Header.HeaderId, indexPath);
headerView.Text = "Supplementary View";
return headerView;
}
}
And finally created:
public class Header : UICollectionReusableView
{
public static NSString HeaderId = new NSString("UserSource1");
UILabel label;
public string Text {
get {
return label.Text;
}
set {
label.Text = value;
SetNeedsDisplay ();
}
}
[Export ("initWithFrame:")]
public Header (RectangleF frame) : base (frame)
{
label = new UILabel (){
Frame = new RectangleF(0,0,300,50),
BackgroundColor = UIColor.Red};
AddSubview (label);
BackgroundColor = UIColor.White;
}
}
I've put a breakpoint on the GetViewForSupplementaryElement method but it never gets called. I've also set the following in my StoryBoard:
What am I missing?!
After many attempts of not being able to get the above to work, I manually set UICollectionViewFlowLayout whilst initiating the UIContainerView. Seems to have done the trick, but not sure why it didn't pick up the settings from my StoryBoard. Here is my working code:
public override void ViewDidLoad ()
{
base.ViewDidLoad ();
CollectionView_Outlet.RegisterClassForCell(typeof(ModifierCell), ModifierCell.CellID);
CollectionView_Outlet.RegisterClassForCell(typeof(ItemOptionCell), ItemOptionCell.CellID);
CollectionView_Outlet.RegisterClassForSupplementaryView (typeof(Header), UICollectionElementKindSection.Header, Header.HeaderId);
CollectionView_Outlet.ShowsHorizontalScrollIndicator = false;
//This is the new bit I added:
var layout = new UICollectionViewFlowLayout ();
layout.HeaderReferenceSize = new CGSize (300, 40);
CollectionView_Outlet.SetCollectionViewLayout (layout, false);
CollectionView_Outlet.Source = new ModifiersSource(this);
CollectionView_Outlet.ReloadData();
}
To get this to work in Xamarin, I had to enable Section Header under accessories (and it crashed in Xamarin, so from XCode). I had to do this even though I'm loading my header from a separate nib/xib into my collection view (but it will also show a reusable cell on the collection view that I don't think I need). Very specific but hopefully this saves someone in a similar situation some time!

UITableView cuts my table view, cannot view the entire TableView[Xamarin, iOS]

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";
}
}
}

UICollectionView Cells not displaying (MonoTouch/Xamarin)

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...

Resources