19 votes

Comment placer UITableView toujours au centre de UIView ?

Je voudrais mettre en place un UITableView au centre d'un UIView . Au départ, il ne comporte que 2 ou 3 rangées. Lorsque l'utilisateur ajoute des rangées supplémentaires, il s'étend dans le sens vertical, tandis que l'ensemble du contenu reste au centre, comme indiqué ci-dessous :

enter image description here

Est-il possible de le faire avec UITableView ?

8voto

akashivskyy Points 11508

Cela peut être fait en utilisant L'interface de l'UIScrollView contentOffset propriété .

  1. Faites en sorte que le cadre de votre tableView se trouve dans les limites :

    tableView.frame = self.view.bounds;
    tableView.autoresizingMask = UIViewAutoresizingFlexibleWidth|UIViewAutoresizingFlexibleHeight;
  2. Déclarer une méthode -layoutTableView :

    - (void)layoutTableView {
        CGSize contentSize = tableView.contentSize;
        CGSize boundsSize = tableView.bounds.size;
        CGFloat yOffset = 0;
        if(contentSize.height < boundsSize.height) {
            yOffset = floorf((boundsSize.height - contentSize.height)/2);
        }
        tableView.contentOffset = CGPointMake(0, yOffset);
    }
  3. Lorsque vous appelez [tableView reloadData] Il suffit d'appeler [self layoutTableView] après.

8voto

Daniel Galasko Points 485

Une autre solution consiste à ajuster l'insertion du contenu de la vue tableau, car la solution du décalage du contenu n'a pas fonctionné pour moi. Voici l'idée de base (insérée dans une sous-classe UITableView personnalisée) :

- (void)reloadData {
    [super reloadData];
    [self centerTableViewContentsIfNeeded];
}

- (void)layoutSubviews {
    [super layoutSubviews];
    [self centerTableViewContentsIfNeeded];
}

- (void)centerTableViewContentsIfNeeded {
    CGFloat totalHeight = CGRectGetHeight(self.bounds);
    CGFloat contentHeight = self.contentSize.height;
    //If we have less content than our table frame then we can center
    BOOL contentCanBeCentered = contentHeight < totalHeight;
    if (contentCanBeCentered) {
        self.contentInset = UIEdgeInsetsMake(ceil(totalHeight/2.f - contentHeight/2.f), 0, 0, 0);
    } else {
        self.contentInset = UIEdgeInsetsZero;
    }
}

Pour ceux qui ont le cœur tendre, voici un terrain de jeu :

import UIKit
import Foundation
import XCPlayground

class CenteredTable: UITableView {
    override func reloadData() {
        super.reloadData()
        centerTableContentsIfNeeded()
    }

    override func  layoutSubviews() {
        super.layoutSubviews()
        centerTableContentsIfNeeded()
    }

    func centerTableContentsIfNeeded() {
        let totalHeight = CGRectGetHeight(bounds)
        let contentHeight = contentSize.height
        let contentCanBeCentered = contentHeight < totalHeight
        if (contentCanBeCentered) {
            contentInset = UIEdgeInsets(top: ceil(totalHeight/2 - contentHeight/2), left: 0, bottom: 0, right: 0);
        } else {
            contentInset = UIEdgeInsetsZero;
        }
    }
}

class DataSource: NSObject, UITableViewDataSource {
    let items = ["Mr", "Anderson", "Welcome", "Back", "We", "Missed", "You"]
    func registerReusableViewsWithTable(tableView: UITableView) {
        tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: "cell")
    }

    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as! UITableViewCell
        cell.textLabel?.text = items[indexPath.row]
        cell.textLabel?.textAlignment = .Center
        return cell
    }

    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return items.count
    }
}

let dataSource = DataSource()
let table = CenteredTable(frame: CGRectMake(0, 0, 300, 800), style: UITableViewStyle.Plain)
table.tableFooterView = UIView(frame: CGRectZero)
let container = UIView(frame: table.frame)
container.addSubview(table)
dataSource.registerReusableViewsWithTable(table)
table.dataSource = dataSource
table.reloadData()
XCPShowView("table", container)
container

5voto

Martin Points 151

Si vous n'utilisez pas d'en-têtes dans le tableau, vous pouvez calculer dynamiquement la hauteur des cellules par rapport à la hauteur limite du tableau.

Félicitations à https://stackoverflow.com/a/15026532/1847601

- (CGFloat) tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    CGFloat contentHeight = 0.0;
    for (int section = 0; section < [self numberOfSectionsInTableView: tableView]; section++) {
        for (int row = 0; row < [self tableView: tableView numberOfRowsInSection: section]; row++) {
            NSIndexPath *indexPath = [NSIndexPath indexPathForRow: row inSection: section];
            contentHeight += [self tableView: tableView heightForRowAtIndexPath: indexPath];
        }
    }
    return (tableView.bounds.size.height - contentHeight)/2;
}

- (UIView *) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
        UIView *view = [[UIView alloc] initWithFrame: CGRectZero];
        view.backgroundColor = [UIColor clearColor];
        return view;
}

3voto

shaunak jagtap Points 31

Pas besoin d'avoir cette logique encombrante. Il suffit d'utiliser la ligne suivante dans cellForRowAt() :

Swift :

tableView.contentInset = UIEdgeInsets(top: (tableView.bounds.height/2 - cell.bounds.height/2), left: 0, bottom: 0, right: 0)

Objective-C :

tableView.contentInset = UIEdgeInsetsMake((tableView.bounds.height/2 - cell.bounds.height/2), 0, 0, 0);

2voto

Giang Points 1208

Swift 3

private func hightTableView() {
    yourTableView.frame = CGRect(x: 0, y: Int((Int(view.frame.height) - rowHeight * yourArrayData.count) / 2), width: widthTable, height: rowHeight * yourArrayData.count)
}

Prograide.com

Prograide est une communauté de développeurs qui cherche à élargir la connaissance de la programmation au-delà de l'anglais.
Pour cela nous avons les plus grands doutes résolus en français et vous pouvez aussi poser vos propres questions ou résoudre celles des autres.

Powered by:

X