35
Эффективность на рубеже UITableView Зимин Александр iOS разработчик UX дизайнер

Эффективность на рубеже UITableView — Александр Зимин

Embed Size (px)

Citation preview

Эффективность на рубеже UITableView

Зимин Александр iOS разработчик

UX дизайнер

realmacsoftware.com/clear

План

• Методы при работе с таблицей • UITableViewController • Ячейки • Кастомизация таблицы

Методы при работе с таблицей

Повторное использование

• init(style: UITableViewCellStyle, reuseIdentifier: String?)

• registerNib(nib: UINib, forCellReuseIdentifier identifier: String)

• registerClass(cellClass: AnyClass, forCellReuseIdentifier identifier: String)

Повторное использование

• dequeueReusableCellWithIdentifier(identifier: String) • dequeueReusableCellWithIdentifier(identifier: String,

forIndexPath indexPath: NSIndexPath)

Подсчет динамической высоты

• tableView(tableView: UITableView, estimatedHeightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat

• tableView.estimatedRowHeight = 85tableView.rowHeight = UITableViewAutomaticDimension

Подсчет динамической высоты

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

Подсчет динамической высоты

Подсчет динамической высоты

UITableViewController

Плюсы

• Скорость интеграции • StaticCells • Удобная интеграция UIRefreshControl • Мелкие локальные улучшения • Автоматическая отмена выделения • Автоматическое отслеживание сдвига при появлении клавиатуры

Минусы

• Нельзя задать размер таблицы • Нельзя добавлять другие UIView на

UITableViewController

Плюсы

• Скорость интеграции • StaticCells • Удобная интеграция UIRefreshControl • Мелкие локальные улучшения • Автоматическая отмена выделения • Автоматическое отслеживание сдвига при появлении клавиатуры

func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { tableView.deselectRowAtIndexPath(indexPath, animated: true) // Any actions here }

Автоматическая отмена выделения

• Подписаться на уведомления о появлении и исчезновении клавиатуры

• Менять contentInset и scrollIndicatorInsets • Не забыть отписаться ;)

Автоматическое отслеживание сдвига при появлении клавиатуры

func registerForKeyboardNotifications() { let notificationCenter = NSNotificationCenter.defaultCenter() notificationCenter.addObserver(self, selector: "keyboardWillBeShown:", name: UIKeyboardWillShowNotification, object: nil) notificationCenter.addObserver(self, selector: "keyboardWillBeHidden:", name: UIKeyboardWillHideNotification, object: nil) }

Автоматическое отслеживание сдвига при появлении клавиатуры

func keyboardWillBeShown(notification: NSNotification) { let keyboardFrame = notification.userInfo?[UIKeyboardFrameEndUserInfoKey]?.CGRectValue() if let frame = keyboardFrame { let contentInsets = UIEdgeInsetsMake(0, 0, frame.height, 0); tableView.contentInset = contentInsets; tableView.scrollIndicatorInsets = contentInsets; } }

Есть свои минусы, если contentInset кастомный

func keyboardWillBeHidden(sender: NSNotification) { tableView.contentInset = UIEdgeInsetsZero tableView.scrollIndicatorInsets = UIEdgeInsetsZero }

Есть свои минусы, если contentInset кастомный

Ячейки

Свой разделитель• Создать класс, который наследуется от

UITableViewCell • Для ячеек, созданных с интерфейса расширяем:

• awakeFromNib() (все связи гарантированно подгружены)

• init(coder aDecoder: NSCoder) • Для ячеек, созданных из кода:

• init(style: UITableViewCellStyle, reuseIdentifier: String?)

Работа с выделением

• setSelected(selected: Bool, animated: Bool) • setHighlighted(highlighted: Bool, animated: Bool) • Задать selectedBackgroundView

Кастомизация таблицы

Пустая таблица

• Отслеживание: • numberOfSectionsInTableView: • tableView(tableView: UITableView,

numberOfRowsInSection section: Int) • Добавление:

• В коде: tableView.backgroundView • На IB: отдельным UIView. По очереди с таблицей делать hidden

https://itunes.apple.com/app/id498958864

Подложка

override func viewDidLoad() { super.viewDidLoad() holderView = UIView(frame: view.frame) holderView.backgroundColor = UIColor.redColor() tableView.addSubview(holderView) // Do any additional setup after loading the view, typically from a nib. }

override func viewWillLayoutSubviews() { super.viewWillLayoutSubviews() holderView.frame = tableView.bounds holderView.frame.origin.y = -tableView.frame.height }

dribbble.com/shots/1948551

Кастомный Pull-To-Refresh• Создать кастомные UIView:

• Он должен отслеживать движение scrollView • Можно сделать через KVO • Можно сделать через target к жесту

• В методе scrollViewDidScroll: отслеживать contentOffset и взаимодействовать с этим View

• Добавить этот view к верху таблицы • Если идет загрузка можно

• Двигать contentInset • Добавлять этот view в header таблицы

realmacsoftware.com/clear

Release to Create Item

• Добавить UIPinchGestureRecognizer на таблицу • Если жест начался, то расчитывать середину жеста и добавлять новую ячейку

• При движении пальцев высчитывать размер для этой ячейки и делать tableView.reloadData()

Release to Create Item

func pinchGestureAction(sender: UIPinchGestureRecognizer) { if sender.state == .Began { startValue = sender.scale let point = sender.locationInView(tableView) insertedIndexPath = tableView.indexPathForRowAtPoint(point) } else if sender.state == .Changed { deltaValue = abs(startValue - sender.scale) } else { insertedIndexPath = nil } reloadCells() }

Самый элементарный вариант

Release to Create Item

func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { if indexPath == insertedIndexPath { return 80 * (1.0 + deltaValue) } return 80 }

Самый элементарный вариант

Спасибо за внимание

Зимин Александр [email protected]

@ziminalex

motivatemeapp.me