63

Александр Зимин "Нестандартная верстка для стандартных компонентов в iOS"

Embed Size (px)

Citation preview

Нестандартная верстка для стандартных компонентов в iOS Зимин Александр

iOS Developer UI Engineer

CocoaHeadsRussia

macOS Developer Co-Founder Организатор

Маркетинг, Дизайн, Аналитика, …

План

• Верстка в iOS • Table View/Collection View • 4 примера-истории • Советы и оптимизация

Верстка в iOS

• Распространение элементов на экране• Отступы, размеры, выравнивания, …• Динамические коллекции

Airbnb

Airbnb

UICollectionView Custom Pagining

UICollectionView Custom Pagining

UITableView UICollectionView

Table View/Collection View

Scroll View

• Контент может быть больше экрана

• Позволяет прокручивать по оси x и y

Cell

Cell

Cell

Table View

Cell

Cell

Cell

Table ViewData Source

Delegate

Cell

Cell

Cell

Table ViewData Source

Delegate

Cell Data

Cell

Cell

Cell

Table ViewData Source

Delegate

Cell Data

“Although UITableView allows vertical scrolling only”

Cell

Cell

Cell

Table ViewData Source

Delegate

Cell Data

“Although UITableView allows vertical scrolling only”

Cell Height

Cell

Cell

Cell

Table ViewData Source

Delegate

Cell Data

“Although UITableView allows vertical scrolling only”

Cell Height

Dynamic Height

Cell

Cell

Cell

Table ViewData Source

Delegate

Cell Data

“Although UITableView allows vertical scrolling only”

Cell Height

Dynamic Height

8

Cell Cell

Cell

Cell Cell

Collection View

Data Source

Delegate

Cell Cell

Cell

Cell Cell

Collection View

Data Source

Delegate

Cell Data

Cell Cell

Cell

Cell Cell

Collection View

Data Source

Delegate

Cell Data

Cell Cell

Cell

Cell Cell

Collection ViewCollection View Layout

Data Source

Delegate

Cell Data

Cell Cell

Cell

Cell Cell

Collection ViewCollection View Layout

LayoutAttributes

Пример

• override func systemLayoutSizeFitting(:, :, :) -> CGSize• Нет ничего плохого в комбинировании Auto Layout и

ручного подсчета• Типы динамического контента:

• Картинки (UIImageView)• Текст (UILabel, UITextView)• Нестандартные элементы (Custom UIView/UIControl)

• UILabel• func sizeThatFits(_ size: CGSize) -> CGSize

• String/NSAttributedString• func boundingRect(with size: CGSize, options:

NSStringDrawingOptions = [], attributes: [String : Any]? = nil, context: NSStringDrawingContext?) -> CGRect

goo.gl/pBdZlI

• UILabel• func sizeThatFits(_ size: CGSize) -> CGSize

• String/NSAttributedString• func boundingRect(with size: CGSize, options:

NSStringDrawingOptions = [], attributes: [String : Any]? = nil, context: NSStringDrawingContext?) -> CGRect

goo.gl/pBdZlI

• UILabel• func sizeThatFits(_ size: CGSize) -> CGSize

• String/NSAttributedString• func boundingRect(with size: CGSize, options:

NSStringDrawingOptions = [], attributes: [String : Any]? = nil, context: NSStringDrawingContext?) -> CGRect

• func boundingRect(with size: CGSize, options: NSStringDrawingOptions = [], context: NSStringDrawingContext?) -> CGRect

goo.gl/pBdZlI

• UIImageView• UIImage

• CGSize• Заранее заданный размер

• Динамическая верстка у таблиц и коллекций существует уже давно (iOS 8+)

• В ней нет ничего плохого, и она вам упростит жизнь• Вы всегда можете комбинировать auto layout и

ручной подсчет• Посчитать размер String/NSAttributedString легко

Итоги демо

Пример

Collection View Layout

Collection View Layout

prepare()

Collection View Layout

prepare()

var collectionViewContentSize: CGSize

Collection View Layout

prepare()

var collectionViewContentSize: CGSize

func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]?

Collection View Layout

prepare()

var collectionViewContentSize: CGSize

func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]?

Collection View Layout

prepare()

var collectionViewContentSize: CGSize

func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]?

func shouldInvalidateLayout(forBoundsChange newBounds: CGRect) -> Bool

• Для любой нестандартной верстки вам хватит UICollectionView

• Нестандартный paging находится там же• Для оптимизации кэшируйте все заранее или в

процессе

Итоги демо

• Заготавливайте ваши значения в prepare()• Кэшируйте значения• Не стоит всегда возвращать true из `shouldInvalidateLayout`• Будьте осторожнее с `estimatedItemSize`

• Не все то золото, что блестит• Не жалейте ресурсов на проверку всех

поддерживаемых iOS• Использование таких элементов по-прежнему

оправдано

Итоги демо

Анимация

• Вы всегда можете показать взаимодействие пользователя с контентом

• Чем интереснее возможность, тем сложнее ее поддерживать

Итоги демо

• Динамическая верстка — это хорошо• Любую верткую можно реализовать на

UICollectionView, и это просто• Чем интереснее возможность — тем больше

ответственность• Все это можно еще анимировать

Итоги

• WWDC 2016 Inclusive App Design — https://developer.apple.com/videos/play/wwdc2016/801/

• WWDC 2016 Making Apps Adaptive Part 1/2 — https://developer.apple.com/videos/play/wwdc2016/222/, https://developer.apple.com/videos/play/wwdc2016/233/

• Подсчет высоты строки — https://goo.gl/pBdZlI

Ссылки

• WWDC 2016 Inclusive App Design — https://developer.apple.com/videos/play/wwdc2016/801/

• WWDC 2016 Making Apps Adaptive Part 1/2 — https://developer.apple.com/videos/play/wwdc2016/222/, https://developer.apple.com/videos/play/wwdc2016/233/

Ссылки

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

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

@ZiminAlex