Friday, November 18, 2016

Swift 3 Making UITableViewRow at the middle of UITableView

Some times we need to display user’s record at the middle of screen. Let’s say we have a race game going on and we need to display always user’s record at the middle of tableview after completion of date while displaying race ranks.

Let’s see how to position particular row in a UITableview at Top/Middle/Bottom position. 

Using scrollToRowAt method of UITableView we can achieve this functionality.




I have a table on my screen which shows all the players and their ranks in the race. Unfortunately my table is having less height to display all players and especially the user’s row as player’s rank is 6 and there are 15 players participated. But I need to display user’s rank visible on the screen.

 In this case we need to scroll the table at the time of displaying ranks after completion of race either at top/bottom or at middle of table as shown below.

To make user’s record at TOP:


      
    @IBAction func userRankAtTop(_ sender: AnyObject) {
        let userIndexPath = IndexPath.init(row: (userRank-1), section: 0)
        self.tableViewRank.scrollToRow(at: userIndexPath, at: .top, animated: true)
    }





To make user’s record at Middle :


      
    @IBAction func userRankAtMiddle(_ sender: AnyObject) {
        let userIndexPath = IndexPath.init(row: (userRank-1), section: 0)
        self.tableViewRank.scrollToRow(at: userIndexPath, at: .middle, animated: true)
    }




To make user’s record at Bottom:


      
    @IBAction func userRankAtBottom(_ sender: AnyObject) {
        let userIndexPath = IndexPath.init(row: (userRank-1), section: 0)
        self.tableViewRank.scrollToRow(at: userIndexPath, at: .bottom, animated: true)
    }






Hope this post is useful. Feel free to comment incase of any queries.