Xamarin.ios CollectionView Delete and Insert Items - visual-studio

I am currently developing an iphone app with xamarin in visual studio. I'm a beginner..
I use a CollectionView. This has a list and includes 8 items with different ID's in the CollectionViewSource.cs:
ProductCategoryList.Add (new ProductCategorys () {Categoryid = 1, ProductCategoryName = "testname", ProductCategoryImage = UIImage.FromFile ( "productcat / maincat / testpic.jpg")});
Now I would like, if an item is pressed, delete All Items and refill it.
In the ProductCategoryCollectionDelegate.cs i have:
Public override Boolean ShouldSelectItem (UICollectionView collectionView, NSIndexPath indexPath)
For the delete and insert I have found these 2 methods
Public void DeleteItems (NSIndexPath [] indexPaths)
Public void InsertItems (NSIndexPath [] indexPaths)
(The xamarin Documentation is very scarce)
How can I use this 2 metodes to completely empty the list and add new items?
thanks for help

I've taken a TableView instead of the CollectionView.
With this function it is possible to directly delete items in the Tablesource class:
public override void CommitEditingStyle(UITableView tableView,
UITableViewCellEditingStyle editingStyle,
Foundation.NSIndexPath indexPath)
{
switch (editingStyle)
{
case UITableViewCellEditingStyle.Delete:
AppDelegate.DAUtil.setBasketItemStatusByBasketID(
basketitems[indexPath.Row].ZBASKETID, "2");
// remove the item from the underlying data source
basketitems.RemoveAt(indexPath.Row);
// delete the row from the table
tableView.DeleteRows(new NSIndexPath[] { indexPath },
UITableViewRowAnimation.Fade);
break;
case UITableViewCellEditingStyle.None:
Console.WriteLine("CommitEditingStyle:None called");
break;
}
}
public override bool CanEditRow(UITableView tableView,
NSIndexPath indexPath)
{
return true;
// return false if you wish to disable editing
// for a specific indexPath or for all rows
}
The Source of the Table is a List. Alternatively, you can reload the TableSource with:
tablename.ReloadData();

Related

Xamarin.iOS - Multiple XIBs in a single UITableView

I am trying to load different nibs into a single UITableView depending on a variable within a model. I seem to have something that looks logical and doesn't crash, however, only 1 of the xibs is being loaded and displayed.
Controller Method:
private void populateTableData()
{
liveTipsTableView.RegisterNibForCellReuse(UINib.FromName("LiveTipCell_", null), "LiveTipCell_");
liveTipsTableView.RegisterNibForCellReuse(UINib.FromName("NewsCell_", null), "NewsCell_");
setListViewSource();
Refresh();
AddRefreshControl();
Add(liveTipsTableView);
liveTipsTableView.Add(RefreshControl);
}
TableSource Method
public override UITableViewCell GetCell(UITableView tableView, NSIndexPath indexPath)
{
var localTip = _tips[indexPath.Row];
if (localTip.NewsItem)
{
CellIdentifier = new NSString("NewsCell_");
NewsCell_ cell = new NewsCell_();
cell = tableView.DequeueReusableCell("NewsCell_") as NewsCell_;
var views = NSBundle.MainBundle.LoadNib("NewsCell_", cell, null);
cell = ObjCRuntime.Runtime.GetNSObject(views.ValueAt(0)) as NewsCell_;
cell.SelectionStyle = UITableViewCellSelectionStyle.None;
cell.BindDataToCell(localTip);
return cell;
}
else
{
CellIdentifier = new NSString("LiveTipCell_");
LiveTipCell_ cell = new LiveTipCell_();
cell = tableView.DequeueReusableCell("LiveTipCell_") as LiveTipCell_;
var views = NSBundle.MainBundle.LoadNib("LiveTipCell_", cell, null);
cell = ObjCRuntime.Runtime.GetNSObject(views.ValueAt(0)) as LiveTipCell_;
cell.SelectionStyle = UITableViewCellSelectionStyle.None;
cell.BindDataToCell(localTip);
return cell;
}
}
I have 2 separate Xib files and they have their own classes which work to populate the views. They all seem to getting used when debugging, it's just a case of the table view is only displaying 1 of these items.
Thanks in advance and please let me know if you need more information to see what's going on.
This is in objective C, but it shouldn't be too hard to convert.
SO Post on a different question

Centering a UIView within a UIScrollView Xamarin.iOS

I am currently trying to center a UIIView inside of a UIScrollView and am having some difficulty in doing so.
Here is the image of my current view:
Here is the code snippet I'm working with:
public void AddView(UIViewController viewCont)
{
this.AddChildViewController(viewCont);
this.mainScrollView.AddSubview(viewCont.View);
viewCont.DidMoveToParentViewController(this);
}
public override void ViewDidLoad()
{
base.ViewDidLoad();
// Perform any additional setup after loading the view, typically from a nib.
var m = new Menu();
//var c = new Camera();
AddView(m);
AddView(c);
CGRect cFrame = c.View.Frame;
cFrame.X = this.View.Frame.Width;
c.View.Frame = cFrame;
this.mainScrollView.ContentSize = new CGSize(this.View.Frame.Width * 2, 1.0);
}
I want to fill this whole view with Green but as you can see, the bottom quarter of the View does not stretch all the way to the bottom.
For the time being, I have removed all constraints because every attempt in adding them results in no successes. I was hoping to get a concrete answer here as to how I could go about centering this view within this UIScrollView.
Thanks
UPDATE: 3-21-2017
My main goal is to have 2 ViewControllers side by side within my UIScrollView that I can navigate to and from using a swipe gesture, like SnapChat. Following, #Digitalsa1nt suggestions, I unfortunately come up with the same issue.
Here are some more pictures:
This first one shows what happens when I only add the 1 view:
This next one shows what happens when I try to add both views to my UIScrollView, only the camera shows:
Finally, here is the code that I am using to back my Camera view:
using Foundation;
using UIKit;
using AVFoundation;
namespace BRB.iOS
{
public partial class Camera : UIViewController
{
AVCaptureSession captureSession;
AVCaptureStillImageOutput stillImageOutput;
AVCaptureVideoPreviewLayer previewLayer;
public Camera() : base("Camera", null)
{
}
public override void ViewDidLoad()
{
base.ViewDidLoad();
// Perform any additional setup after loading the view, typically from a nib.
}
public override void DidReceiveMemoryWarning()
{
base.DidReceiveMemoryWarning();
// Release any cached data, images, etc that aren't in use
}
public override void ViewDidAppear(bool animated)
{
base.ViewDidAppear(animated);
previewLayer.Frame = cameraView.Bounds;
}
public override void ViewWillAppear(bool animated)
{
base.ViewWillAppear(animated);
captureSession = new AVCaptureSession();
captureSession.SessionPreset = AVCaptureSession.Preset1920x1080;
var backCamera = AVCaptureDevice.GetDefaultDevice(AVMediaType.Video);
NSError error;
var input = AVCaptureDeviceInput.FromDevice(backCamera, out error);
if (error == null && captureSession.CanAddInput(input))
{
captureSession.AddInput(input);
stillImageOutput = new AVCaptureStillImageOutput();
stillImageOutput.OutputSettings = new NSDictionary(AVVideo.CodecKey, AVVideo.CodecJPEG);
if (captureSession.CanAddOutput(stillImageOutput))
{
captureSession.AddOutput(stillImageOutput);
previewLayer = new AVCaptureVideoPreviewLayer(captureSession);
previewLayer.VideoGravity = AVLayerVideoGravity.ResizeAspect;
previewLayer.Connection.VideoOrientation = AVCaptureVideoOrientation.Portrait;
cameraView.Layer.AddSublayer(previewLayer);
captureSession.StartRunning();
}
}
}
}
}
I usually override 'didlayoutsubviews' for making changes to the views within my UIScrollViews. The below worked for me.
public void AddView(UIViewController viewCont)
{
AddChildViewController(viewCont);
mainScrollView.AddSubview(viewCont.View);
viewCont.DidMoveToParentViewController(this);
}
public override void ViewDidLayoutSubviews()
{
base.ViewDidLayoutSubviews();
// Ensure our contentinsets are 0 so we don't have any blank space
mainScrollView.ContentInset = new UIEdgeInsets(0, 0, 0, 0);
// set the contentsize to the bounds of the container view within.
mainScrollView.ContentSize = View.Bounds.Size;
}
public override void ViewDidLoad()
{
base.ViewDidLoad();
// Perform any additional setup after loading the view, typically from a nib.
var m = new Menu();
//var c = new Camera();
AddView(m);
AddView(c);
}

How to drag and drop rows in NSTableView in Mac

I have struck with one point i.e now I have got a list of data using NSTableView but what my requirement is, able to drag and drop that rows from one row position to another row position. please give any suggestion for get out this problem. Thanks in advance.
My sample code
Within your NSTableViewDataSource subclass implement WriteRows, ValidateDrop and AcceptDrop and register which Drag/Drop targets your NSTableView accepts. In this case you are only accepting Drops from within your own NSTableView.
Assign a name that will be used for valid drag operations on this NSTableView:
// Any name can be registered, I find using the class name
// of the items in the datasource is cleaner than a const string
string DragDropType = typeof(Product).FullName;
Register the drag types for your NSTableView:
ProductTable.RegisterForDraggedTypes(new string[] { DragDropType });
Implement drag/drop methods on your NSTableViewDataSource:
public override bool WriteRows(NSTableView tableView, NSIndexSet rowIndexes, NSPasteboard pboard)
{
var data = NSKeyedArchiver.ArchivedDataWithRootObject(rowIndexes);
pboard.DeclareTypes(new string[] { DragDropType }, this);
pboard.SetDataForType(data, DragDropType);
return true;
}
public override NSDragOperation ValidateDrop(NSTableView tableView, NSDraggingInfo info, nint row, NSTableViewDropOperation dropOperation)
{
tableView.SetDropRowDropOperation(row, dropOperation);
return NSDragOperation.Move;
}
public override bool AcceptDrop(NSTableView tableView, NSDraggingInfo info, nint row, NSTableViewDropOperation dropOperation)
{
var rowData = info.DraggingPasteboard.GetDataForType(DragDropType);
if (rowData == null)
return false;
var dataArray = NSKeyedUnarchiver.UnarchiveObject(rowData) as NSIndexSet;
Console.WriteLine($"{dataArray}");
// Move hack for this example... you need to handle the complete NSIndexSet
tableView.BeginUpdates();
var tmpProduct = Products[(int)dataArray.FirstIndex];
Products.RemoveAt((int)dataArray.FirstIndex);
if (Products.Count == row - 1)
Products.Insert((int)row - 1 , tmpProduct);
else
Products.Insert((int)row, tmpProduct);
tableView.ReloadData();
tableView.EndUpdates();
return true;
}

Disabled button in UITableViewCell Xamarin.iOs

I have UITableView and each cell has button and text. Actual cell shouldn't be clickable, but button should. When I run in simulator I can hit button, but when deploy to device it is disabled. (edited)
Tried to follow many different steps to fix it from this post Button in UITableViewCell not responding under ios 7, such as ContentView.UserInteractionEnabled = False; for cell.
All of those for native iOS, maybe for Xamarin there are something else?
Any ideas what am I missing?
UITableViewCell code
this.DelayBind(() =>
{
var set = this.CreateBindingSet<CalendarCell, ActivityModel>();
set.Bind(CustomerNameLabel).To(a => a.Subject);
set.Bind(MarkAsMeetingButton).For(a => a.Hidden).WithConversion("ActivityTypeToVisibility");
set.Bind(MarkAsMeetingButton).To(a => a.SendMessageToViewModelCommand).CommandParameter(BindingContext);
set.Apply();
});
ContentView.UserInteractionEnabled = false;
UItableView code
public override void ViewDidLoad()
{
base.ViewDidLoad();
var source = new TableSource(CalendarList);
var set = this.CreateBindingSet<CalendarView, CalendarViewModel>();
set.Bind(source).To(vm => vm.CalendarList);
set.Apply();
CalendarList.Source = source;
CalendarList.ReloadData();
}
public class TableSource : MvxSimpleTableViewSource
{
private List<IGrouping<DateTime, ActivityModel>> GroupedCalendarList = new List<IGrouping<DateTime, ActivityModel>>();
public TableSource(UITableView calendarView) : base(calendarView, "CalendarCell", "CalendarCell")
{}
public override UITableViewCell GetCell(UITableView tableView, NSIndexPath indexPath)
{
var currentSection = GroupedCalendarList[indexPath.Section].ToList();
var item = currentSection[indexPath.Row];
var cell = GetOrCreateCellFor(tableView, indexPath, item);
var bindable = cell as IMvxDataConsumer;
if (bindable != null)
bindable.DataContext = item;
return cell;
}
public override nint RowsInSection(UITableView tableview, nint section)
{
return (nint)GroupedCalendarList[(int)section].Count();
}
public override UIView GetViewForHeader(UITableView tableView, nint section)
{
var label = new UILabel();
var currentDate = DateTime.Now;
var titleText = GroupedCalendarList[(int)section].FirstOrDefault().ScheduledStart.Value.Date;
return label;
}
public override nint NumberOfSections(UITableView tableView)
{
return (nint)GroupedCalendarList.Count;
}
public override void ReloadTableData()
{
if (ItemsSource == null) return;
var groupedCalendarList = (ItemsSource as List<ActivityModel>).GroupBy(cl => cl.ScheduledStart.Value.Date).ToList();
GroupedCalendarList = new List<IGrouping<DateTime, ActivityModel>>(groupedCalendarList);
base.ReloadTableData();
}
}
This code works absolutely fine for simulator, but doesn't work on device, UIButton in each cell is disabled.
As #Luke said in the comments of your question said, do not use ContentView.UserInteractionEnabled = false;, since this disables any touch events on the whole view of your cell.
To achieve what you need, implement the UITableViewDelegate method ShouldHighlightRow and return false:
public override bool ShouldHighlightRow(UITableView tableView, NSIndexPath rowIndexPath) {
return false;
}
Then, the cells will not get highlighted on tap, and the RowSelected method will not get called, but your button will be clickable!

Dismiss view controller doesn't deallocate memory

I have several modals in my application , here is extentions method what I use for every of them:
public static void CloseAndDismissViewController (this NSViewController vc)
{
vc.View.Window.Close ();
vc.DismissController (vc);
vc.RemoveFromParentViewController ();
}
But I doesn't deallocate memory, here is screen shot from profiler :
finally , such cases cause application crashes....
I'm using PrepareForSegue method to pass data from source to destination vc, like this one :
public override void PrepareForSegue (NSStoryboardSegue segue, NSObject sender)
{
if (segue.Identifier.Equals ("ImageInfo")) {
var vc = segue.DestinationController as InfoViewController;
vc.SetData (item);
}
}

Resources