在Xamarin IOS中滚动时,在集合视图中添加项目

时间:2016-05-02 14:18:22

标签: xamarin xamarin.ios

我想在用户滚动视图时将新项添加到集合视图中。 我能够成功添加项目,但滚动条移动到顶部。 请找到我的以下代码。

ViewControll代码:

public partial class ViewController : UIViewController
{
    UIWindow window;

    UICollectionViewController simpleCollectionViewController;
    UICollectionViewFlowLayout flowLayout;
    UIScrollView viewColle = new UIScrollView( new CGRect(0,100,UIScreen.MainScreen.Bounds.Width, 500));

    int count = 2;
    protected ViewController(IntPtr handle) : base(handle)
    {
        // Note: this .ctor should not contain any initialization logic.
    }

    public override void ViewDidLoad()
    {
        base.ViewDidLoad();
        viewColle.BackgroundColor = UIColor.Green;
        // Perform any additional setup after loading the view, typically from a nib.
        // Flow Layout
        flowLayout = new UICollectionViewFlowLayout () {
            HeaderReferenceSize = new CGSize (0, 0),
            SectionInset = new UIEdgeInsets (0, 0, 0, 0),
            ScrollDirection = UICollectionViewScrollDirection.Vertical,
            MinimumInteritemSpacing = 5, // minimum spacing between cells
            MinimumLineSpacing = 5 // minimum spacing between rows if ScrollDirection is Vertical or between columns if Horizontal
        };
        simpleCollectionViewController = new MyCollectionViewController (flowLayout,count);
        simpleCollectionViewController.CollectionView.ContentInset = new UIEdgeInsets (0, 0, 0, 0);

        UIButton btnClick = new UIButton()
        {
            Frame = new CoreGraphics.CGRect(0,0,UIScreen.MainScreen.Bounds.Width,50),
            BackgroundColor = UIColor.Gray
        };

        btnClick.SetTitle("Click", UIControlState.Normal);

        btnClick.TouchUpInside += (sender, e) => {          
            window = new UIWindow(UIScreen.MainScreen.Bounds);
            count++;
            //var nav = new UINavigationController(simpleCollectionViewController);

            //window.RootViewController = nav;
            //window.MakeKeyAndVisible();
            if (count > 3)
                count = count / 3;


            if (count == 1)
            {
                simpleCollectionViewController = new ListViewController (flowLayout,count,2);
                simpleCollectionViewController.CollectionView.ContentInset = new UIEdgeInsets (0, 0, 0, 0);
                viewColle.AddSubview(simpleCollectionViewController.View);
            }
            else if (count == 2)
            {
                simpleCollectionViewController = new MyCollectionViewController (flowLayout,count);
                simpleCollectionViewController.CollectionView.ContentInset = new UIEdgeInsets (0, 0, 0, 0);
                viewColle.AddSubview(simpleCollectionViewController.View);

            }
            else if (count == 3)
            {
                simpleCollectionViewController = new DetailViewController (flowLayout,1);
                simpleCollectionViewController.CollectionView.ContentInset = new UIEdgeInsets (0, 0, 0, 0);
                viewColle.AddSubview(simpleCollectionViewController.View);
            }


            //viewColle.Frame = new CGRect(0, 100, UIScreen.MainScreen.Bounds.Width, 500);
            nfloat height0 = 0;
            CGRect contentRect0 = new CGRect();
            foreach (UIView view in viewColle.Subviews) {
                height0 += view.Bounds.Height;
            }
            contentRect0.Size = new CGSize(View.Bounds.Width, height0 );
            viewColle.ContentSize = contentRect0.Size;

            //viewColle.ContentSize = new CGSize(simpleCollectionViewController.View.Bounds.Width, 2000);
            View.AddSubview(btnClick);
            View.AddSubview(viewColle);
        };

        viewColle.AddSubview(simpleCollectionViewController.View);
        //viewColle.Frame = new CGRect(0, 100, UIScreen.MainScreen.Bounds.Width, 500);
        nfloat height1 = 0;
        CGRect contentRect1 = new CGRect();
        foreach (UIView view in viewColle.Subviews) {
            height1 += view.Bounds.Height;
        }
        contentRect1.Size = new CGSize(View.Bounds.Width, height1 );
        viewColle.ContentSize = contentRect1.Size;


        CGRect contentRect = new CGRect();
        foreach (UIView view in viewColle.Subviews) {
            contentRect = view.Frame;
        }
        viewColle.ContentSize = contentRect.Size;

        //viewColle.ContentSize = new CGSize(simpleCollectionViewController.View.Bounds.Width, 2000);
        View.AddSubview(btnClick);
        View.AddSubview(viewColle);

        viewColle.Scrolled += (sender, e) => { 
            UIAlertView alert = new UIAlertView("Scrolled Alert", "Scroller "+ count.ToString(), null, "Cancel", null);
            alert.Show();

            if (count > 3)
                count = count / 3;


            if (count == 1)
            {
                simpleCollectionViewController = new ListViewController (flowLayout,count,10);
                simpleCollectionViewController.CollectionView.ContentInset = new UIEdgeInsets (0, 0, 0, 0);
                viewColle.AddSubview(simpleCollectionViewController.View);
            }
            else if (count == 2)
            {
                simpleCollectionViewController = new MyCollectionViewController (flowLayout,count);
                simpleCollectionViewController.CollectionView.ContentInset = new UIEdgeInsets (0, 0, 0, 0);
                viewColle.AddSubview(simpleCollectionViewController.View);

            }
            else if (count == 3)
            {
                simpleCollectionViewController = new DetailViewController (flowLayout,1);
                simpleCollectionViewController.CollectionView.ContentInset = new UIEdgeInsets (0, 0, 0, 0);
                viewColle.AddSubview(simpleCollectionViewController.View);
            }

            nfloat height = 0;
            CGRect contentRect2 = new CGRect();
            foreach (UIView view in viewColle.Subviews) {
                height += view.Bounds.Height;
            }
            contentRect2.Size = new CGSize(View.Bounds.Width, height );
            viewColle.ContentSize = contentRect2.Size;

            //viewColle.Frame = new CGRect(0, 100, UIScreen.MainScreen.Bounds.Width, 500);
            //viewColle.ContentSize = new CGSize(simpleCollectionViewController.View.Bounds.Width, 2000);
            View.AddSubview(btnClick);
            View.AddSubview(viewColle);

        };

    }

    public override void DidReceiveMemoryWarning()
    {
        base.DidReceiveMemoryWarning();
        // Release any cached data, images, etc that aren't in use.
    }
}

ListViewController代码:

public partial class ListViewController : UICollectionViewController
{

    static NSString animalCellId = new NSString ("AnimalCell");
    static NSString headerId = new NSString ("Header");
    List<IProduct> products;
    int devideValue = 0;
    public ListViewController (UICollectionViewLayout layout,int divValue, int count) : base (layout)
    {
        devideValue = divValue;
        products = new List<IProduct> ();
        for (int i = 0; i < count; i++) {
            Product pr = new Product();
            pr.id = i;
            pr.Price = i;
            products.Add (pr);
        }
    }

    [Export ("collectionView:layout:sizeForItemAtIndexPath:")]
    public virtual CGSize GetSizeForItem (UICollectionView collectionView, UICollectionViewLayout layout, NSIndexPath indexPath)
    {
        //For 2 items devide by 2
        var width = (float)(UIScreen.MainScreen.Bounds.Width/devideValue);
        return new CGSize (width - 10, 125);
    }

    public override void ViewDidLoad ()
    {
        base.ViewDidLoad ();

        CollectionView.RegisterClassForCell (typeof(ProductCell1), animalCellId);
        CollectionView.RegisterClassForSupplementaryView (typeof(Header), UICollectionElementKindSection.Header, headerId);

        UIMenuController.SharedMenuController.MenuItems = new UIMenuItem[] {
            new UIMenuItem ("Add to Cart?", new Selector ("addCart"))
        };
    }

    public override nint NumberOfSections (UICollectionView collectionView)
    {
        return 1;
    }

    public override nint GetItemsCount (UICollectionView collectionView, nint section)
    {
        return products.Count;
    }

    public override UICollectionViewCell GetCell (UICollectionView collectionView, NSIndexPath indexPath)
    {
        var productCell = (ProductCell1)collectionView.DequeueReusableCell (animalCellId, indexPath);

        var product = products [indexPath.Row];

        productCell.Image = product.Image;
        productCell.Price = product.Price;
        productCell.Product = product.ProductName;

        return productCell;
    }

    public override UICollectionReusableView GetViewForSupplementaryElement (UICollectionView collectionView, NSString elementKind, NSIndexPath indexPath)
    {
        var headerView = (Header)collectionView.DequeueReusableSupplementaryView (elementKind, headerId, indexPath);
        //headerView.Text = "Product View";
        //headerView.btnText = "Click";
        return headerView;
    }

    public override void ItemHighlighted (UICollectionView collectionView, NSIndexPath indexPath)
    {
        var cell = collectionView.CellForItem (indexPath);
        cell.ContentView.BackgroundColor = UIColor.Red;
    }

    public override void ItemUnhighlighted (UICollectionView collectionView, NSIndexPath indexPath)
    {
        var cell = collectionView.CellForItem (indexPath);
        cell.ContentView.BackgroundColor = UIColor.Green;

        ProductCell1 productCell = (ProductCell1)collectionView.DequeueReusableCell (animalCellId, indexPath);
        int itemIndex = (int)indexPath.Item;
        Product prodt = new Product();
        for (int i = 0; i < products.Count; i++)
        {
            if (indexPath.Item == i)
            {
                prodt = (Product)products[i];
                break;
            }
        }

        UIAlertView alert = new UIAlertView("Selected Item", prodt.id.ToString(), null, "Cancel", null);
        alert.Show();
    }

    //public override void ItemSelected(UICollectionView collectionView, NSIndexPath indexPath)
    //{
    //  //var cell = collectionView.CellForItem (indexPath);

    //  base.ItemSelected(collectionView, indexPath);
    //}

    public override bool ShouldHighlightItem (UICollectionView collectionView, NSIndexPath indexPath)
    {
        return true;
    }

    // for edit menu
    public override bool ShouldShowMenu (UICollectionView collectionView, NSIndexPath indexPath)
    {
        return true;
    }

    public override bool CanPerformAction (UICollectionView collectionView, Selector action, NSIndexPath indexPath, NSObject sender)
    {
        // Selector should be the same as what's in the AddCart UIMenuItem
        if (action == new Selector ("addCart"))
            return true;
        else
            return false;
    }

    public override void PerformAction (UICollectionView collectionView, Selector action, NSIndexPath indexPath, NSObject sender)
    {
        System.Diagnostics.Debug.WriteLine ("code to perform action");
    }

    // CanBecomeFirstResponder and CanPerform are needed for a AddCart menu item to appear
    public override bool CanBecomeFirstResponder {
        get {
            return true;
        }
    }

}

public class ProductCell1 : UICollectionViewCell
{
    UIImageView imageView;
    UILabel productName;
    UILabel manufacturer;
    UIView cellViewContainer;
    UILabel price;
    [Export ("initWithFrame:")]
    public ProductCell1 (CGRect frame) : base (frame)
    {
        BackgroundView = new UIView{ BackgroundColor = UIColor.DarkGray };
        SelectedBackgroundView = new UIView{ BackgroundColor = UIColor.Green };

        ContentView.Layer.BorderColor = UIColor.LightGray.CGColor;
        ContentView.Layer.BorderWidth = 2.0f;
        ContentView.BackgroundColor = UIColor.Gray;

        cellViewContainer = new UIView ();
        cellViewContainer.AutoresizingMask = UIViewAutoresizing.FlexibleWidth | UIViewAutoresizing.FlexibleHeight;

        imageView = new UIImageView (UIImage.FromBundle ("placeholder.png"));
        productName = new UILabel {
            Text = "Name",
            TextColor = UIColor.Black,
            BackgroundColor = UIColor.White,
            TextAlignment = UITextAlignment.Left
        };
        manufacturer = new UILabel {
            Text = "Price",
            TextColor = UIColor.Black,
            BackgroundColor = UIColor.Red,
            TextAlignment = UITextAlignment.Left
        };
        price = new UILabel {
            Text = "Price",
            TextColor = UIColor.Black,
            BackgroundColor = UIColor.Red,
            TextAlignment = UITextAlignment.Left
        };

        //productName.Frame = new CGRect (5, 5, labelWidth, labelHeight);
        //price.Frame = new CGRect (5, labelHeight, labelWidth, labelHeight);
        //imageView.Frame = new CGRect (labelWidth, 0, labelWidth, ContentView.Bounds.Height - 2); 


        imageView.Frame = new CGRect (3,3, ContentView.Bounds.Width/2, ContentView.Bounds.Height-3); 
        productName.Frame = new CGRect (ContentView.Bounds.Width/2 + 5, 3, ContentView.Bounds.Width/2  - 5, 20);
        manufacturer.Frame = new CGRect (ContentView.Bounds.Width/2 + 5, 23, ContentView.Bounds.Width/2 - 5, 20);
        price.Frame = new CGRect (ContentView.Bounds.Width/2 + 5, 43, ContentView.Bounds.Width/2 - 5, 20);
        ContentView.AddSubviews (new UIView[] { imageView, productName, manufacturer, price });
    }

    public void UpdateCell ()
    {
        productName.Frame = new CGRect (10, 10, ContentView.Bounds.Width / 2, ContentView.Bounds.Height / 3);
        price.Frame = new CGRect (20, 20, ContentView.Bounds.Width / 2, ContentView.Bounds.Height / 3);
    }

    public UIImage Image {
        set {
            imageView.Image = value;
        }
    }

    public string Product {
        set {
            productName.Text = value;
        }
    }

    public double Price {
        set {
            price.Text = value.ToString ("$0.00");
        }
    }

    [Export ("addCart")]
    void AddCart ()
    {
        // Put all your addCart menu behavior code here
        Console.WriteLine ("addCart in the cell");
    }


    public override bool CanPerform (Selector action, NSObject withSender)
    {
        if (action == new Selector ("addCart"))
            return true;
        else
            return false;
    }
}

添加项目后,查看滚动条移动到顶部。请任何人建议我解决这个问题。

0 个答案:

没有答案