Пользовательский размер подкачки для TableView с заголовком в Swift (прокрутка по одной ячейке за раз)
У меня есть UITableView с несколькими разделами, каждый с заголовком. Размер таблицы таков, что один заголовок и одна ячейка занимают весь кадр таблицы. Я хотел бы позволить пользователю прокручивать таблицу только по одной ячейке за раз. Когда я установил paging = enabled, прокрутка не работает должным образом, поскольку таблица прокручивает только один кадр таблицы за раз, а не одну ячейку за раз. Это приводит к нежелательному смещению, которое продолжает увеличиваться при прокрутке таблицы.
Мои исследования до сих пор показывают, что мне нужно переопределить scrollViewWillBeginDragging. Посмотрите, например, UITableView с пользовательским поведением, похожим на пейджинг. Но каждый пост, который я читал на эту тему, должен был быть до Swift, потому что все это в Objective C.
Пожалуйста, предложите код Swift для выполнения постраничного разбиения на ячейки для таблицы с заголовками разделов. Хотя сам пейджинг может потребоваться отключить, решение должно быть как можно ближе к истинному пейджингу.
Ниже приведен код для определения размеров моей таблицы. Размер каркаса стола - 475.
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
if (condition == true) {
return CGFloat(425)
}
else {
return CGFloat(375)
}
}
func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
if (condition == true) {
return CGFloat(47)
}
else {
return CGFloat(90)
}
}
ОБНОВЛЕНИЕ: верхний ответ здесь ( принудительное переключение UITableView для прокрутки к верхам ячеек) также представляется актуальным. Но, опять же, это все в Задаче C. Если ответы в любой из этих ссылок окажутся правильными, будет достаточно простого перевода этого ответа на Swift.
ОБНОВЛЕНИЕ 2 Я почти понял это. Но крайние случаи не работают (то есть в самом верху и в самом низу таблицы). То есть, я получаю пейджинговое действие прокрутки, кроме случаев, когда я пытаюсь прокрутить вниз до последней ячейки в таблице. Нет привязки к этой последней камере. Просто прокручивается как обычно. Я подозреваю, что это как-то связано с frame.origin.y этой последней ячейки.
Пожалуйста, помогите мне разобраться с этими краями. Код ниже:
viewDidLoad() {
self.tableView.decelerationRate = UIScrollViewDecelerationRateFast
}
var lastContentOffset:CGPoint!
var initialIndexPath:NSIndexPath?
func scrollViewWillBeginDragging(scrollView: UIScrollView) {
lastContentOffset = CGPointMake(scrollView.contentOffset.x, scrollView.contentOffset.y)
var visibleCellIndexes = tableView.indexPathsForVisibleRows() as! [NSIndexPath]
initialIndexPath = visibleCellIndexes[0]
}
var scrolledToPath:NSIndexPath?
func scrollViewWillEndDragging(scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>) {
if (scrollView == self.tableView) {
var lastIndexPath:NSIndexPath!
var nextIndexPath:NSIndexPath!
if let p = scrolledToPath {
lastIndexPath = scrolledToPath
}
else if let u = initialIndexPath {
lastIndexPath = initialIndexPath
}
if (lastContentOffset.y <= scrollView.contentOffset.y) {
// scrolling down
if (lastIndexPath.row == numRows(lastIndexPath.section)-1) {
// last row in section
if (lastIndexPath.section == numSections(self.tableView)-1) {
// last section
nextIndexPath = lastIndexPath
}
else {
nextIndexPath = NSIndexPath(forRow: 0, inSection: lastIndexPath.section+1)
}
}
else {
nextIndexPath = NSIndexPath(forRow: lastIndexPath.row+1, inSection: lastIndexPath.section)
}
}
else if (lastContentOffset.y > scrollView.contentOffset.y) {
// scrolling up
if (lastIndexPath.row == 0) {
// first row in section
if (lastIndexPath.section == 0) {
// first section
nextIndexPath = lastIndexPath
}
else {
nextIndexPath = NSIndexPath(forRow: numRows(lastIndexPath.section-1)-1, inSection: lastIndexPath.section-1)
}
}
else {
nextIndexPath = NSIndexPath(forRow: lastIndexPath.row-1, inSection: lastIndexPath.section)
}
}
scrolledToPath = nextIndexPath
var headerHeight = CGFloat(47)
if (condition == true) {
headerHeight = CGFloat(90)
}
var rectOfNextIndexPath:CGRect = self.tableView.rectForRowAtIndexPath(nextIndexPath)
targetContentOffset.memory.y = rectOfNextIndexPath.origin.y - headerHeight
}
}
1 ответ
Исправлена. Размеры в моем табличном виде испортили конечные случаи. После того, как я убедился, что размеры ячеек были правильными, все заработало. Ниже приведено решение для прокрутки страниц в виде страниц в Swift.
viewDidLoad() {
self.tableView.decelerationRate = UIScrollViewDecelerationRateFast
}
var lastContentOffset:CGPoint!
var initialIndexPath:NSIndexPath?
func scrollViewWillBeginDragging(scrollView: UIScrollView) {
lastContentOffset = CGPointMake(scrollView.contentOffset.x, scrollView.contentOffset.y)
var visibleCellIndexes = tableView.indexPathsForVisibleRows() as! [NSIndexPath]
initialIndexPath = visibleCellIndexes[0]
}
var scrolledToPath:NSIndexPath?
func scrollViewWillEndDragging(scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>) {
var lastIndexPath:NSIndexPath!
var nextIndexPath:NSIndexPath!
if let p = scrolledToPath {
lastIndexPath = scrolledToPath
}
else if let u = initialIndexPath {
lastIndexPath = initialIndexPath
}
if (lastContentOffset.y <= scrollView.contentOffset.y) {
// scrolling down
if (lastIndexPath.row == numRows(lastIndexPath.section)-1) {
// last row in section
if (lastIndexPath.section == numSections(self.tableView)-1) {
// last section
nextIndexPath = lastIndexPath
}
else {
nextIndexPath = NSIndexPath(forRow: 0, inSection: lastIndexPath.section+1)
}
}
else {
nextIndexPath = NSIndexPath(forRow: lastIndexPath.row+1, inSection: lastIndexPath.section)
}
}
else if (lastContentOffset.y > scrollView.contentOffset.y) {
// scrolling up
if (lastIndexPath.row == 0) {
// first row in section
if (lastIndexPath.section == 0) {
// first section
nextIndexPath = lastIndexPath
}
else {
nextIndexPath = NSIndexPath(forRow: numRows(lastIndexPath.section-1)-1, inSection: lastIndexPath.section-1)
}
}
else {
nextIndexPath = NSIndexPath(forRow: lastIndexPath.row-1, inSection: lastIndexPath.section)
}
}
scrolledToPath = nextIndexPath
var headerHeight = CGFloat(47)
if (condition == true) {
headerHeight = CGFloat(90)
}
var rectOfNextIndexPath:CGRect = self.tableView.rectForRowAtIndexPath(nextIndexPath)
targetContentOffset.memory.y = rectOfNextIndexPath.origin.y - headerHeight
}