Xamarin iOS Autolayout: Resize width and vertical scroll automatically for various devices while keeping the horizontal scroll disabled

前端 未结 4 959
慢半拍i
慢半拍i 2020-12-22 00:21

I want to create a page which has a vertical but no horizontal scroll. It must adjust width of the content and vertical scroll automatically as per screen size.

Som

4条回答
  •  生来不讨喜
    2020-12-22 00:59

    In a custom renderer for Xamarin.Forms i've written my UITableViewController like this:

    _controller = new InfoFieldItemsTableViewController();
    _controller.TableView.SeparatorStyle = UITableViewCellSeparatorStyle.None;
    _controller.TableView.SeparatorColor = UIColor.Clear;
    _controller.TableView.AllowsSelection = false;
    // http://useyourloaf.com/blog/self-sizing-table-view-cells/
    _controller.TableView.RowHeight = UITableView.AutomaticDimension;
    

    In my controller i am doing this to register all potential cell candidates:

        private void RegisterCells()
        {
            foreach (var tuple in InfoFieldCellMapping.Map)
            {
                this.TableView.RegisterNibForCellReuse(tuple.Value.Item1, tuple.Value.Item2);
            }
        }
    
        public override void ViewDidLoad()
        {
    
            RegisterCells();
    
            base.ViewDidLoad();
        }
    

    I am doing this in my controller so cells resize themselves depending on how much height they need:

        public override nfloat EstimatedHeight(UITableView tableView, NSIndexPath indexPath)
        {
            return 100;
        }
    

    Now all you need to do is create cell files from within your IDE which should be .xib files and design them in the editor using autolayout (so they can adapt to orientation changes automatically).

    Within your TableViews datasource all that's left to do is mapping between your data item and it's corresponding cell similar to:

    public override UICollectionViewCell GetCell(UICollectionView collectionView, NSIndexPath indexPath) 
    {
        var dataItem = Items[indexPath.Row];
        var key = ""; // use info from data item to figure out which key identifies your table cell to dequeue the correct kind of cell
        var cell = collectionView.DequeueReusableCell(key, indexPath) as UICollectionViewCell;
    }
    

    That's all you need really. In my scenario i am mapping fields which may contain different controls for date entries, number entries, long texts, short texts etc etc.

    I hope that helps

提交回复
热议问题