2015-08-31 3 views
2

Мне нужно прокрутить таблицуView до indexPath сразу после моего экрана. Вот что я пробовал, но он не работает при запуске. Он работает только при загрузке tableView, а затем я нажимаю кнопку, которая прокручивает tableView.мгновенно прокрутить таблицуView to indexPath

func scrollTableViewToCell() { 
    let indexPath = NSIndexPath(forItem: 8, inSection: 1) 
    self.tableView.scrollToRowAtIndexPath(indexPath, atScrollPosition: .Middle, animated: true) 
} 

Я также попытался это, но он не работает, как мне нужно:

func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) { 
    println(indexPath) 
    println(NSIndexPath(forRow: tableView.indexPathsForVisibleRows()!.last!.row, inSection: 2)) 
    if indexPath == NSIndexPath(forRow: tableView.indexPathsForVisibleRows()!.last!.row, inSection: 0) { 
     scrollTableViewToCell() 
    } 
} 

Я также попробовал это)

override func viewDidLayoutSubviews() { 
    self.view.layoutIfNeeded() 
    scrollTableViewToCell() 
} 

Может кто-нибудь сказать мне, как знаете, когда tableView загрузил все ячейки, а затем прокрутил его до NSIndexPath (forItem: 8, inSection: 1)?

UPDATE ::

Вот как я загрузить данные в Tableview:

func numberOfSectionsInTableView(tableView: UITableView) -> Int { 
    return years.count 
} 

func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { 
    return allInfo[years[section]]!.count 
} 

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { 
    var cell = tableView.dequeueReusableCellWithIdentifier("tutionTableViewCell") as! TuitionTableViewCell 
    cell.selectionStyle = .None 

    let info = allInfo[years[indexPath.section]]! as [String: String?] 

    cell.monthLabel.text = months[indexPath.row] 
    if info[months[indexPath.row]]! != nil { 
     cell.tuitionLabel.hidden = false 
     cell.tuitionLabel.text = info[months[indexPath.row]]! 
    } else { 
     cell.tuitionLabel.hidden = true 
    } 
    if info[months[indexPath.row]]! == "Nog te betalen" { 
     cell.monthLabel.textColor = UIColor(hex: 0xff0000).colorWithAlphaComponent(0.87) 
     cell.tuitionLabel.textColor = UIColor(hex: 0xff0000).colorWithAlphaComponent(0.87) 
    } else { 
     cell.monthLabel.textColor = UIColor.blackColor().colorWithAlphaComponent(0.87) 
     cell.tuitionLabel.textColor = UIColor.blackColor().colorWithAlphaComponent(0.87) 
    } 
    return cell 
} 

func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? { 
    return years[section] 
} 

func tableView(tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) { 
    let header: UITableViewHeaderFooterView = view as! UITableViewHeaderFooterView 
    header.textLabel.font = UIFont(name: "Roboto-Regular", size: 16) 
    header.textLabel.text = self.tableView(self.tableView, titleForHeaderInSection: section) 
    let headerFrame = header.frame 
    header.textLabel.frame = headerFrame 
    header.textLabel.textColor = UIColor.blackColor().colorWithAlphaComponent(0.54) 
    header.textLabel.backgroundColor = UIColor(hex: 0xf9f9f9) 
    header.contentView.backgroundColor = UIColor(hex: 0xf9f9f9) 
} 

func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { 
    return 35 
} 

ВТОРАЯ ОБНОВЛЕНИЕ ::

Мои жёстко данные:

var years: [String] = ["2015", "2016", "2017"] 
var months: [String] = ["Januari", "Februari", "Maart", "April", "Mei", "Juni", "Juli", "Augustus", "September", "Oktober", "November", "December"] 
var allInfo: [String: [String: String?]] = [String: [String: String?]]() 

override func viewDidLoad() { 
    self.tableView.separatorStyle = .None 
    self.tableView.rowHeight = UITableViewAutomaticDimension 
    self.tableView.estimatedRowHeight = 150.0 

    allInfo[years[0]] = ["Januari": "300,00", "Februari": "300,00", "Maart": "300,00", "April": "300,00", "Mei": "300,00", "Juni": "300,00", "Juli": "300,00", "Augustus": "300,00", "September": "300,00", "Oktober": "300,00", "November": "300,00", "December": "300,00"] 
    allInfo[years[1]] = ["Januari": "300,00", "Februari": "300,00", "Maart": "300,00", "April": "300,00", "Mei": "300,00", "Juni": "300,00", "Juli": "300,00", "Augustus": "300,00", "September": "Nog te betalen", "Oktober": nil, "November": nil, "December": nil] 
    allInfo[years[2]] = ["Januari": nil, "Februari": nil, "Maart": nil, "April": nil, "Mei": nil, "Juni": nil, "Juli": nil, "Augustus": nil, "September": nil, "Oktober": nil, "November": nil, "December": nil] 

    tableView.reloadData() 
    scrollTableViewToCell() 
} 
+0

Вы пытаетесь прокрутить в 'viewDidAppear'? – dasdom

+4

вы должны вызывать 'scrollTableViewToCell()' только после того, как ваша таблица полностью загружена, например, после '[table reloadData]' – Fonix

+0

@Fonix Я пробовал этот 'viewDidLoad() {tableView.reloadData() scrollTableViewToCell()}', но он прокручивается в неправильное положение. Я хочу, чтобы мой TableView прокручивал до indexPath по центру экрана, но он отображается вверху [screenshot] (http://oi58.tinypic.com/opcsph.jpg). – mikle94

ответ

0

Ma ка, что вы реализовали метод estimatedHeightForRowAtIndexPath -

func tableView(tableView: UITableView, estimatedHeightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { 
    return 44 
} 

Как вы прокрутку TableView непосредственно в строку, которая находится ниже ячеек, которые никогда не были оказавших TableView не может правильно раскладывать клетки, если она не знать размер «недостающих» ячеек.

Реализация этого метода в тестовом приложении разрешила проблему с прокруткой и странное «щелканье», которое я видел при прокрутке.

Кроме того, вы должны вызвать super.viewDidLoad() в методе viewDidLoad

+0

О, мы написали ответы в одно и то же время!) Да, я тоже нашел эту проблему. Большое вам спасибо за вашу помощь! – mikle94

0

большое спасибо @ Paulw11 за помощь мне с моей проблемой.

Я решил, удалив эти две строки кода в viewDidLoad:

self.tableView.rowHeight = UITableViewAutomaticDimension 
self.tableView.estimatedRowHeight = 150.0 

Теперь она прокручивается по мере необходимости!

Кроме того, прокрутка задержка была удалена путем добавления прокрутки анимации:

self.tableView.scrollToRowAtIndexPath(indexPath, atScrollPosition: .Middle, animated: true) 
Смежные вопросы