Xcode previews что это

Apple анонсировала preview Xcode 4

Apple анонсировала выход preview-версии среды разработки Xcode 4 для разработчиков с подпиской.
Ниже перевод информации, размещенной на официальной странице.

Xcode представляет полный набор инструментов для создания приложений под Mac, iPhone и iPad. С выходом новой версии Xcode 4 инструментарий был перепроектирован так, чтобы стать быстрее, проще в использовании и значительно более полезным, чем когда-либо ранее. Интегрированная среда разработки (IDE) Xcode понимает каждый нюанс Вашего проекта, определяя ошибки как в синтаксисе, так и в логике, и даже исправит Ваш код за Вас! Проще говоря, Xcode 4 поможет Вам писать код лучше.

Xcode 4 имеет совершенно новый пользовательский интерфейс, основанный на опробованных технологиях, которые сама Apple использует для построения Mac OS X и iOS. На этих технологиях основаны более четверти миллиона приложения для Mac, iPhone и iPad.

Единое окно

Xcode previews что это. Смотреть фото Xcode previews что это. Смотреть картинку Xcode previews что это. Картинка про Xcode previews что это. Фото Xcode previews что это

Первое, что заметят в Xcode 4 опытные пользователи — это то, что множество окон, используемых при решении Ваших ежедневных рабочих задач разработчика, были объединены в одно единственное окно. Рабочая область Xcode 4 содержит несколько уникальных элементов пользовательского интерфейса, которые упрощают работу на многими задачами (и даже в нескольких проектах одновременно), не замусоривая Вашу рабочую область. Ваш редактор всегда остается впереди и в центре.

Навигаторы

Xcode previews что это. Смотреть фото Xcode previews что это. Смотреть картинку Xcode previews что это. Картинка про Xcode previews что это. Фото Xcode previews что это

Панель быстрого перехода (Jump Bar)

Xcode previews что это. Смотреть фото Xcode previews что это. Смотреть картинку Xcode previews что это. Картинка про Xcode previews что это. Фото Xcode previews что это

В верхней части каждого окна навигатора расположена панель пути, показывающая относительное положение текущего файла. Кликните по любому положению в пути, чтобы немедленно перейти к любому другому файлу на соответствующем уровне. Панель быстрого перехода настолько эффективна, что Вы можете выделить все свое рабочее пространство для исходного кода, используя панель для быстрого перехода между файлами проекта.

Interface Builder — внутри

Xcode previews что это. Смотреть фото Xcode previews что это. Смотреть картинку Xcode previews что это. Картинка про Xcode previews что это. Фото Xcode previews что это

Interface Builder был полностью интегрирован с IDE Xcode 4 — больше нет отдельного приложения.
При выборе файла интерфейса (.nib/.xib) в Вашем проекте, редактор интерфейса откроется внутри Xcode. При открытии окна Utility будет показан полный перечень инспекторов интерфейса, а также библиотека элементов управления и объектов пользовательского интерфейса. Для формирования интерфейса Вашего будущего приложения перетащите элемент управления из библиотеки и отпустите над окном.

Отличная идея: Вы можете перетаскивать соединения прямо между элементами пользовательского интерфейса и исходным кодом. Новое раздельное размещение редактора Xcode 4 позволяет легко связать Ваши действия и слоты (outlets) простым перетаскиванием соединения на существующий код — один жест и все готово. Пока еще нет кода, готового для соединения? Xcode создаст новый слот или действия для Вас. Просто перетащите на пустое пространство и Xcode сгенерирует для Вас код.

Xcode previews что это. Смотреть фото Xcode previews что это. Смотреть картинку Xcode previews что это. Картинка про Xcode previews что это. Фото Xcode previews что это

Assistant

Xcode previews что это. Смотреть фото Xcode previews что это. Смотреть картинку Xcode previews что это. Картинка про Xcode previews что это. Фото Xcode previews что это

Пишите ли Вы код или проектируете интерфейс — изменений в схеме работы теперь не происходит. Даже малейшая правка может иметь каскадный эффект для всего Вашего проекта. Часто Вам нужно видеть больше, чем просто текущий файл. Также бывает нужно видеть связанные документы.
С новым Xcode Assistant, двухоконное расположение окон в редакторе становится значительно более функциональным. Когда Вы включите Assistant, среда разработки будет предвидеть, какие иные файлы Вам может быть необходимо увидеть в процессе работы. Редактируете новый производный класс? Assistant покажет Вам код класса, от было выполнено наследование. Пишете новый код реализации? Assistant автоматически покажет соответствующий заголовочный файл. При проектировании интерфейса Assistant будет показывать соответствующий контроллер, невероятно упрощая создание соединений с кодом путем перетаскивания. При проектировании модели данных Вы увидите классы, соответствующие Вашим моделям — и все автоматически.

Компилятор LLVM 2.0

Компилятор LLVM — это технология компилятора нового поколения с открытым исходным кодом, используемая в высокопроизводительных проектах по всему миру и разработанная под руководством инженеров Apple из команды компилятора. С компилятором LLVM 2.0, полный стек компилятора — от парсера до оптимизатора кода — полностью поддерживает C, Objective-C и C++.
LLVM — быстрый компилятор. Он компилирует код в 2 раза быстрее GCC, при этом создавая приложения, которые также работают быстрее. Это происходит потому, что компилятор был спроектирован с самого начала как набор высокооптимизированных библиотек, легко расширяемый, легко оптимизируемый и спроектированный для архитектуры современных чипов.
В Xcode 4 компилятор — это больше, чем утилита командной строки. LLVM полностью интегрирован в IDE. Подсветка синтаксиса, автоматическое завершение кода и любая другая функция, управляемая индексированным кода теперь обрабатывается парсером LLVM. Если компилятор знает о символе, то и IDE знает о нем. C, C++, и Objective-C все точно понимаются в момент редактирования, точно так же словно в момент их сборки.

Fix-it («почини это»)

Xcode previews что это. Смотреть фото Xcode previews что это. Смотреть картинку Xcode previews что это. Картинка про Xcode previews что это. Фото Xcode previews что это

Используя встроенный движок LLVM, Xcode 4 может делать больше, чем просто автозавершение кода и подсветку синтаксиса. Новая функция Fix-it предупреждает Вас об ошибках во время набора кода. Точно также как текстовый процессор подсвечивает ошибки орфографии, Xcode 4 подсвечивает типичные ошибки кодирования без необходимости сначала нажимать кнопку «Собрать» (Build).
Но почему останавливаться только на предупреждениях?
Xcode previews что это. Смотреть фото Xcode previews что это. Смотреть картинку Xcode previews что это. Картинка про Xcode previews что это. Фото Xcode previews что это
IDE знает что-Вы-делаете-не-так, потому что она понимает Ваш код. Она понимает его настолько хорошо, что может даже исправить его для Вас. Одно нажатие клавиши может исправить присвоение на сравнение или добавить пропущенную точку с запятой.
Fix-it — отличное дополнение при вводе текста к жесткому тестированию, выполняемому функцией «Собрать и проанализировать» (Build and Analyze). Статический анализатор Xcode пройдет по тысячам потенциальных веток в поисках мест, где код будет вести себя неожиданном образом. Например, такие ошибки как ошибки выделения памяти, никогда невыполняемые ветки case или неправильно сформированные циклы.
Вместе функции «Fix-it» и «Build and Analyze» помогут Вам обнаружить ошибки задолго до Ваших пользователей.

Редактор версий

Xcode previews что это. Смотреть фото Xcode previews что это. Смотреть картинку Xcode previews что это. Картинка про Xcode previews что это. Фото Xcode previews что это

Новый редактор версий Xcode 4 позволяет проще увидеть две версии Вашего исходного кода рядом друг с другом, непосредственно в редакторе. Что более важно, редактор версий — это новый способ мышления об управлении кодом, т.к. окно сравнения одновременно является временной осью. Перетащите ползунок в середине и Вы отправитесь назад во времени по Вашему проекту, сравнивая две версии.
Редактор версий также может показать подробный лог прошедших событий и отследить виновника для предыдущих версий проекта. Сложные команды утилит управления конфигурациями обрабатываются «за сценой». Возможно даже управлять несколькими проектами в одном рабочем пространстве Xcode 4, имея один проект в Subversion, а другой в Git, с автоматическими обновлениями для обоих.

Новый отладчик

Xcode 4 представляет LLDB, новый отладочный движок, предоставленный Apple в проект LLVM.org (с открытым исходным кодом). Как и LLVM, новый движок LLDB спроектирован с самого начала так, чтобы потреблять значительно меньше памяти и быть словно ракета, когда дело доходит до производительности.
Новый отладочный движок LLDB прекрасно подходит для нового интерфейса отладки Xcode 4. Когда Ваше приложение запущен, навигатор показывает трассировку стека, которую Вы можете сворачивать и разворачивать для просмотра кадров стека (stack frames) в процессе отладки. По мере Вашего продвижения, Вы можете сфокусироваться на отладке отдельного потока (thread), а затем нажать «продолжить», чтобы следить за конкретным потоком исполнения. Многоядерная отладка в Xcode 4 теперь настолько же проста, как и многоядерное программирование с использованием блоков (blocks) и Grand Central Dispatch (прим. перев.: что это?).

Инструменты для Xcode 4

Xcode previews что это. Смотреть фото Xcode previews что это. Смотреть картинку Xcode previews что это. Картинка про Xcode previews что это. Фото Xcode previews что это
Все инструменты имеют пользовательский интерфейс, полностью совместимый с новыми возможностями Xcode 4. Используя новые схемы запуска Xcode 4, становится легче, чем когда либо создать среду тестирования для запуска Вашего приложения в Инструментах. Это может включать в себя запуск Инструментов в «отложенном режиме», сохранение интерфейса сбора данных вне экрана и сохранение системных ресурсов для запуска и измерения Вашего приложения.

Также доступны новые инструменты сбора данных, включая OpenGL ES для отслеживания производительности графики iPhone, новую утилиту мониторинга выделений памяти, которая поможет обнаружить неожиданный рост потребления памяти, Профилировщик Времени (Time Profiler) на iOS для сбора выборок с малыми накладными расходными и полная Трассировка Системы (System Trace) для глубокого понимания того, как происходит взаимодействие между всеми системными процессами.
Теперь Инструменты позволяют решать еще больше проблем с меньшими затратами, чем когда-либо ранее.

Источник

Xcode уроки. Урок 1. Интерфейс IDE Xcode и шаблоны

На сегодняшний день мобильные технологии охватывают всё больше сфер деятельности человека. Рост рынка мобильных приложений показывает значимость, удобность и актуальность использования мобильных устройств.

По мере технического прогресса мобильные устройства получают новые технические возможности, растет скорость и надежность при передаче данных в каналах беспроводной связи. Мобильные телефоны, смартфоны, планшетные компьютеры становятся основной частью цифровой жизни человека.

С каждым днём растёт количество разработчиков, увеличивается количество приложений и пользователей, а также все больше и больше компаний понимают необходимость создания собственных приложений для повышения конкурентоспособности, поэтому необходимо изучить новые инструменты: языки программирования, среды разработки для ОС.

Цель урока: ознакомление с интерфейсом и возможностями среды Xcode. Обучение тому, как пользоваться и с чего начать для создания первого проекта. Получение знаний для создания проекта, используя специальные шаблоны среды, а также изменяя основные настройки проекта. Получение представлений о каждом файле проекта Xcode, а также о их основном предназначении.

Краткое описание IDE Xcode

Компания Apple создала мощные наборы инструментов для разработчиков ПО. Все эти инструменты объединены в одном приложении под названием Xcode, который позволяет разработчику создавать, тестировать, развертывать и распространять приложения.

Xcode previews что это. Смотреть фото Xcode previews что это. Смотреть картинку Xcode previews что это. Картинка про Xcode previews что это. Фото Xcode previews что это

Xcode – это интегрированный программный продукт компании Apple для разработки программного обеспечения для платформ: iOS, macOS, WatchOS и tvOS. Xcode уникален и поддерживает целый ряд технологий, он содержит все, что необходимо разработчику: интуитивно понятный редактор кода с подсветкой синтаксиса, расширенные возможности отладки программ, простой, но многофункциональный интерфейс и многое другое.

Xcode поддерживает языки программирования: C, C++, Objective-C, Java, AppleScript, Python, Ruby, ResEdit и Swift, с различными моделями программирования, включая, но не ограничиваясь, Cocoa, Carbon и Java. Сторонние разработчики добавили поддержку GNU Pascal, Free Pascal, Ada, C#, Perl и D.

Самая первая версия Xcode была выпущена в 2001 году, с тех пор было выпущено целых 9 версий этой программы, которая распространяется в Apple Store абсолютно бесплатно для разработчиков. На сегодняшний день, 9 версия Xcode – это самая свежая стабильная версия. С момента выхода первой версии данной IDE в 2001 году, среда разработки менялась в положительную сторону. Внедрялись новые технологии и наборы инструментов, которые помогали разработчику в процессе создания приложений.

Interface Builder

Xcode previews что это. Смотреть фото Xcode previews что это. Смотреть картинку Xcode previews что это. Картинка про Xcode previews что это. Фото Xcode previews что это

Interface Builder – Это интерфейсный редактор, который позволяет проектировать и создавать полный пользовательский интерфейс мобильных приложений. Является составной частью IDE Xcode. Компания Apple позаботилась о том, чтобы интерфейс Xcode был дружелюбен и понятен:

Xcode previews что это. Смотреть фото Xcode previews что это. Смотреть картинку Xcode previews что это. Картинка про Xcode previews что это. Фото Xcode previews что это

На рисунке цифрами обозначены отдельные элементы программы:

Левую, правую и нижние панели легко можно скрыть кнопками, расположенными в правом верхнем углу, чтобы сосредоточиться на процессе написания программы. Левая панель может отображать разную информацию: когда активна первая иконка, то панель отображает все файлы, которые относятся к текущему проекту.

Настройки проекта Xcode и файлы проекта

Если кликнуть по названию проекта (в данном случае “Tip Calculator”), то можно перейти к основным настройкам проекта. В настройках проекта всегда можно изменять некоторые параметры, такие как: версия приложения, разработчик, версия iOS, для которой ведется разработка, устройства, для которых ведется разработка и многое другое.

Xcode previews что это. Смотреть фото Xcode previews что это. Смотреть картинку Xcode previews что это. Картинка про Xcode previews что это. Фото Xcode previews что это

Файл проекта «AppDelegate.swift» содержит в себе специальный программный код с функциями. Этот файл является важным и содержит следующие некоторые методы:

1) Методы, необходимые для конфигурации и загрузки приложения в память;

2) Методы, которые должны вызываться при сворачивании приложения или, например, при входящем звонке;

3) Методы, которые срабатывают при переходе в фоновый режим работы приложения;

4) Методы обновления информации приложения при переходе в активный режим работы;

5) Методы удаления приложения из памяти при закрытии его пользователем.

Файл проекта «ViewController.swift» содержит в себе основной программный код любого приложения, написанного в Xcode.

Файл проекта «Main.storyboard» является основным при создании интерфейса приложения, ведь именно в нём содержится информация о расположении различных элементов (текстовых полей, кнопок, количества окон и др.). Из библиотеки объектов легко можно перетаскивать элементы будущего интерфейса (label, button, text field и многие др.) и помещать на экран приложения.

Например, на рисунке можно увидеть, что на главном экране приложения добавлены из библиотеки: два TextField, три Lable, Button и Switch. К этим элементам можно привязывать код или выводить какую-либо информацию, а также изменять их размеры, перемещать и менять различные свойства: цвет, шрифт и т.д.

Xcode previews что это. Смотреть фото Xcode previews что это. Смотреть картинку Xcode previews что это. Картинка про Xcode previews что это. Фото Xcode previews что это

Так как в Xcode можно создать универсальное приложение для устройств с разным размером экрана, то существуют и инструменты, которые помогают настроить адаптацию под различные размеры экрана и ориентации устройства (альбомные или портретные).

Файл проекта «images. xcassets» содержит в себе иконки и изображения, которые в дальнейшем будут использоваться в проекте.

Файл проекта «LaunchScreen.xib» – это то, что показывается пользователю при загрузке приложения. Здесь можно добавлять любые элементы из библиотеки объектов, которые будут создавать общий вид, являющийся, по сути, загрузочной заставкой приложений.

Создание проекта и шаблоны в Xcode

Xcode previews что это. Смотреть фото Xcode previews что это. Смотреть картинку Xcode previews что это. Картинка про Xcode previews что это. Фото Xcode previews что это

Создать проект в среде Xcode несложно. Чтобы это сделать, необходимо запустить Xcode и выбрать «Create a new Xcode project» на первоначальном экране приветствия.

Apple предоставляет по умолчанию множество различных шаблонов проектов для iOS, каждый из которых полезен для начала работы над различными проектами:

Шаблон Single View Applications самый простой и является отправной точкой для многих приложений. Создаётся совершенно пустой интерфейс, который может изменяться разработчиком по своему усмотрению.

Шаблон Master-Detail App подходит, если планируется, что приложение будет активно использовать элемент UITableView. По умолчанию Xcode создаёт проект, который имеет вид таблицы, куда пользователь может добавить строку, используя в правом углу панель навигации.

Шаблон Page-Based Application создаёт страницу-книгу, позволяя пользователю перелистывать страницы. Такой шаблон подходит, если планируется создать приложение, которое отображает информацию в книжном формате, т.е. пользователь будет просматривать страницы свайпом влево или вправо.

Шаблон Tabbed Applications создаёт панель вкладок и две готовые вкладки. При переключении вкладок происходит переход к разным частям приложения.

Шаблон Games позволяет создавать игры, используя технологии Apple OpenGL ES, GLKit, Scene Kit и Metal.

Для создания базового приложений подойдёт шаблон Single View. После того, как шаблон выбран, необходимо нажать кнопку «Next» для перехода на следующее окно:

Xcode previews что это. Смотреть фото Xcode previews что это. Смотреть картинку Xcode previews что это. Картинка про Xcode previews что это. Фото Xcode previews что это

Далее необходимо заполнить поля:

Xcode previews что это. Смотреть фото Xcode previews что это. Смотреть картинку Xcode previews что это. Картинка про Xcode previews что это. Фото Xcode previews что это

Product Name (Название продукта) – название будущего приложения. Название проекта в будущем можно изменить во время разработки.

Team (Команда) – Название команды разработчиков, занимающихся разработкой приложений. В данном случае выбран сертификат одного человека «персональной команды».

Organization Name (Название организации) и Organization Identifier (Идентификатор организации) – поля требуются для указания компании, которая разрабатывает программное обеспечение. Необходимо для того, чтобы подать заявку в App Store для публикации приложения. Идентификатор организации в стиле обозначения обратного имени домена. Например, если название организации «togu», то идентификатор организации будет «com.togu».

Language (Язык) – поле со списком, состоящее из двух языков, на одном из которых будет происходить разработка мобильного приложения: Swift или Objective C.

Источник

Mastering Xcode Previews

Xcode 11 displays previews of your user interface right in the editor, streamlining the edit-debug-run cycle into a seamless workflow. Learn how previews work, how to optimize the structure of your SwiftUI app for previews, and how to add preview support to your existing views and view controllers.

Resources

Related Videos

WWDC 2019

So let me start with a little story.

Let’s say a designer comes to you and brings a mockup for a screen that they have been working on for your Disney application. You take this mockup, and you take it to your desk, and you work on it. You build it. And you bring it back to show your designer your work.

So let me give you another example.

Or at a different dynamic content size. Or maybe even on a different device.

And there is a real tension between verifying that your UI and your app looks as good as it can possibly look under a variety of circumstances. And, you know, actually shipping your app to the App Store that we as developers are all familiar with.

But the question is, how? How does this work? How does it do it? Well when you enable Previews in your application, Xcode actually builds your app in a special way.

And because the amount of code that needs to be recompiled for every change is significantly smaller than the entirety of the rest of your application, Xcode can continuously and repeatedly do this for every change that you make.

And that means the feedback on your changes is much, much quicker.

But there is a whole class of changes that Xcode can optimize even further. So for changes that involve only the literal values, like strings or numbers, no recompilation is required at all.

And it’s important to note here that the Xcode Previews is not a representation of what Xcode thinks your view will look like when you run the application.

It is actually building and running your code.

So now the question is, how does Xcode know what to show you? Well it turns out all you need to tell Xcode what view to preview and how to configure the data is a little bit of code. And all you do is you implement a small type that conforms to a PreviewProvider protocol, which is a part of a SwiftUI framework.

And that particle has one requirement, just a Previews property that you implement. And then you return some content. And really, what your return out of here is completely up to you.

And because this code lives as a part of your application as well, it’s compiled alongside the rest of your application code. The same story applies for the configuration code as it does for the view. So you also can use custom logic in here and custom resources and even runtime configuration. There are several advantages beyond that to using code to configure your previews.

For instance, since this is just SwiftUI code, this configuration code is just SwiftUI. If you know how to create SwiftUIView, you already automatically know how to configure a preview for it.

Also, you can write a preview once, put it in your source control, and share it with your team. So that means you write a preview, and the rest of your team can benefit.

To tell you more about how to configure them to take advantage of them to the fullest, please welcome Nate. Anton told you that previews are code.

I would like to show you how to write one.

The Xcode Previews team has decided to take a trip to the zoo.

There are a lot of animals at the zoo, and we want to make sure not to miss even one.

Naturally, being the app developers that we are, we couldn’t help ourselves but had to build an application to track the animals at the zoo.

I have been working on that application. In particular, the main user interface for it is a list of animals at the zoo.

In that list is displayed a number of animal cells.

Let me show you what I have got so far.

You pass to that method the name of the device you want to see a preview on.

And almost immediately in the canvas, you see the device displaying your view. Now as I am looking at the device, this iPhone SE showing the animal cell, I am seeing a problem.

The rightmost text is truncated. Let’s go ahead and fix that.

To do so, I’ll change this HStack into a VStack.

Immediately, the canvas updates, showing us exactly what we want.

Now Anton’s daily carry is an iPhone 10r. To make sure that his device shows this cell well, we could change the argument that we are passing to previewDevice. But there is an easier way.

Specifically, we can embed this view in a group.

To do so, Command-click on the AnimalCell and scroll down to Embed in Group.

Then add a second instance of the animal cells to it, this time calling previewDevice with iPhone 10r.

Now we see, in the canvas, a preview for our cell running on two devices.

Scientific names of animals are often written in italics. Let’s go ahead and make that change right now.

Now in the canvas we can validate that our change looks correct on both devices. This is so easy. It’s great to be able to see our views previewed on the devices that our users are actually using. But for smaller views like a cell, it’s also great to be able to focus in on the details we really care about and to strip away that extraneous chrome.

To do so, the Previews API provides the method «Preview Layout.» Now the Preview Layout method can be passed three different arguments. First, you can specify the device. That’s actually what’s being used by default and what’s displayed in the canvas right now. Secondly, you can use a specific size that you want your preview to be displayed as. This is super useful if you know that your view is going to be embedded in some larger view at a particular size. And finally, you can use Size That Fits. This is useful if you want your view to be able to determine the size of the preview based on its content.

You know, the two texts, the red fox and the family name below it, Canidae, are a little too indistinct. I want them to be visually distinctive, one from the next. So I am going to go ahead and make the red fox be bold.

To do that, I’ll Command-click on the Text and scroll down to the Inspect action, then change the weight to Bold.

The source editor gets new code added to it, and the previews refresh in response.

A lot of users like to take advantage of dynamic font sizes. Let’s take a look at what our view will look like when the user changes dynamic font size to extra-large.

Because the preview of API is part of SwiftUI, we can take advantage of all of SwiftUI when we are writing our previews. In particular, in this case we can use the environment modifier and specify the value for the Size category keypath to be extra-large.

Now it’s great to be able to so easily change the size category that we are seeing our view at. But what would be even better would be to be able to see our view displayed at every single content size category at once. What we could do is embed this view in a group and, and for each different one, create a different animal cell. But that’s very repetitive, and there is a better way.

SwiftUI has the for each feature. To use it, I am going to Command-click on the animal cell, scroll down to Repeat.

And now, for each of the integers from 0 to 5, we get a preview. But what I actually want is for each of the Content Size category cases to have a preview, and for each of those cases to specify into the environment the value for the size category keypath to be that case.

Code is inserted in the source editor, and we get an update in the canvas. This looks great.

One problem you may encounter when you have a number of previews in the canvas like this is that it’s difficult to distinguish between the different previews. You need to know which configuration in your code, in your implementation of the Previews static property correspond to which preview in the canvas.

To help out with that problem, the Previews API provides the method «Preview Display Name.» In this case we want to use the name of the content size category we are displaying.

And right below each preview, we see the content size category. Yeah. This is really great.

The Previews API is concise and extremely powerful.

To tell you about how to use Xcode features to make the most of your previews, here’s Anton.

So I am going to jump in into this demo and finish building the animal cell that Nate was working on. And the first thing I am going to do is I am going to focus on this Red fox image placeholder. Now when we shipped this application, we expected data to come from a network service that we are going to provide. But we haven’t built the networking code yet, and so I don’t have the data to populate my view. And so I am using placeholder data here, and it’s easy enough for strings like we do for fox here. But for images the story is a little bit more complicated. That’s because I could add an asset that’s a placeholder asset for use in my previews.

So now that we know that I have these preview assets in an asset catalog, I can show you that under my Preview Data. Here’s my asset catalog. And in it I already have an image for the red fox that I was going to use as a placeholder.

OK, so this looks good. There is some shadows and some overlays. This looks nice, but look what happened to my code now. Most of this view for the cell is now sort of dominated by this image treatment code.

I am probably done with this treatment, and I don’t really want to lose the details here. So I am going to extract this by Command-clicking on the image.

I am clicking on the image and picking Extracted View.

And Xcode locates a new SwiftUI view in the same file down below, so let me rename it. I will call it «Animal Image.» And I will give it some argument, which is my image name. And if I scroll down here, here’s my animal image.

Easy enough. I will wire in my input. And I have refreshed my preview. Yes, thanks. I think this looks pretty cool, too.

My preview that I was just looking at disappears. I am back to the context of the cell. And so my list went away. What I really want to do is I want to make my edits to the cell while looking at it in the context in which it will actually appear, which is the list.

One thing I could do is I could just add another preview here that just previews the list. Like I told you before, you could really provide any content as a part of your preview.

And let me show you what you can do. I will navigate back to Animal List, and I will see the preview for my list like I saw before. And it’ll use this little Pin button in the bottom left corner. And I’ll click it. And what this will do is it will pin the current preview to this preview; and as I navigate in a different files, notice what happens.

This preview stays up. Thank you.

There is a little header here that tells me «Hey, you are not looking at exactly the preview that you have from this file before. This comes from Animal List.» So just so you know. And if I wanted to get to my original previews from this file, I can just scroll down and all of them are still here. So I didn’t any context at all. So now that I know what I need to do, I can Command-click on my VStack and call Inspect. And it can inspect and change my alignment here, give it some padding.

Let’s see what happens.

Now that I did these two things, I am going to replace my animal cell with this selectable animal cell. And that’s really all I need. I can refresh my previews, and you can see nothing really changed.

Well why is that? It’s because the selection here is optional. By default nothing is selected in my list, and I can’t see the things that I just did what I did. Now of course I can click the Live Vote button, take this UI.

Now what I can do is I can change my previews to instead of previewing Animal List, previewing Animal List content.

So, so far we have been looking at Xcode Previews and how they work with SwiftUI. But they can do a lot more for you for your application. And to tell you more about that, please welcome Nate. Thank you Anton.

Not all of you are going to be writing brand new applications starting this week using SwiftUI.

Many of you have apps in the App Store and apps you have been working on for years.

Because SwiftUI has rich integration with UIKit, AppKit, and WatchKit, and because the Previews API is part of SwiftUI, Xcode Previews works great with all of those frameworks as well.

In our zoo application, when you tap on the Info button that Anton added to the bottom of a cell, we are going to display a detail screen for the animal that’s selected. It turns out that that screen is written as a UIViewController called «Animal View Controller.» Let me show you the code for it. First, I am going to go ahead and close the canvas by pressing Command-Return and then switch over to the Animal View Controller.

I’d like to show you what this view controller looks like. But rather than building and running, I am going to go ahead and create a preview instead.

Now previews are just code, so we absolutely could go ahead and create the preview right alongside this UIViewController in this file.

In this case, I am going to create a brand new type to conform to that protocol, namely, «AnimalViewControllerPreview.» Now the preview provider protocol has a single requirement that you must implement, namely, the Static Previews Property.

SwiftUI has rich support for embedding UIViewControllers into SwiftViews in the form of Representables. To learn more about that, check out the session «Integrating SwiftUI.» In our case, because we want to represent a UIViewController, we want to add a conformant to UIViewController representable.

And for expediency, I am just going to go ahead and add that right alongside PreviewProvider to the AnimalViewControllerPreviews type.

Now for our purposes, the UIViewController representable protocol has three requirements that we need to implement. The first is to specify the type of UIViewController that’s being represented.

In our case, that’s the AnimalViewController.

Secondly, we need to describe how to create one of these AnimalViewControllers from the context it exists inside. That context includes things like whether the user is running in light or dark mode and what the dynamic font size is.

In this case, I have already added a little wrapper class around UIStoryBoard; and I am loading an AnimalViewController from it.

The third requirement that we need to implement is updateUIViewController.

This allows us to change the appearance of our view controller based on changes in the environment, among other things.

In our case, we just want to create a preview.

So I am going to go ahead and leave this implementation blank. Now that we have a conformants to the UIViewController representable protocol, we are ready to implement that Previews method.

Specifically, we’ll return an instance of the type that conforms to UIViewController representable, namely, AnimalViewController Previews.

With just those few lines of code, you can see a preview for your UIViewController in Xcode. Let’s take a look at it. I am going to close the project navigator and open the canvas by pressing Command-Option-Return.

Because we added new methods in the source editor, we will need to rebuild.

There is an underlay view beneath the text above the image. It’s semi-opaque, so that the text should be readable. But clearly it’s not opaque enough. So let’s go ahead and crank that opacity up enough. I am going to pin this preview so that we can keep looking at it as we make the change, and switch over to the AnimalViewController file.

And in this file I’ll change the alpha of that underlay view to 0.5.

Immediately, the canvas updates, showing us our preview for our ViewController with that change.

Anton showed you the AnimalActionViewController. I have been working on that, so I already added a preview for it. Let me show it to you. I am going to go ahead and unpin this AnimalViewController preview, clicking the Pin button in the bottom left of the canvas, and then switch over to the AnimalActionsViewController representable.

And there is a preview for this AnimalActionViewController.

The team is discussing the button on the far right there, and we feel that IImage is not quite appropriate. It’s not quite consistent with the platform. Let’s go ahead and fix that now. I am going to open the AnimalActionViewController file.

And, you know, I was taking a trip down Memory Lane when wrote this, so I went ahead and did it in Objective-C. Thank you. Thank you. It’s a great language.

And I’ll change the system image that we are populating the Info button with to info.circle.

Xcode Previews works not just with SwiftUI and not just with Swift files, but even with your Objective-C code written in UIKit, AppKit, and WatchKit. And moreover, it works with all of the source files that Xcode understands.

You have seen how Xcode Previews can really accelerate your workflow.

And thanks to using a cell model, it’s extremely explicit what data is going into what field on the view.

With that said, we could have actually used an animal model object and passed that directly into the view.

We didn’t, for two big reasons.

The first is that using a view model makes it way easier to add new previews.

A good pattern to consider for your PreviewProvider implementation is to add a static array of view model. And in your implementation of the Static Previews property, to iterate over that array of view model and populate your view.

This is useful when you encounter a new data configuration that will result in a different view layout.

All you need to do is create a view model and add it to that array.

Then you’ll get a new preview in the canvas showing your new view layout.

Before getting to the second big reason that we decided to use view models in the zoo application, I want to wax a little philosophical for a moment if you’ll bear with me.

The model layer of your application includes a rich object draft.

Even in our zoo application, we have a zoo model object.

And that zoo model object is only one among many of the animals in a clade. On the other side, that animal model object has within a genome. How are you going to display that information to your users? Well, not all at once. For example, you don’t want to add a genome to your animal cell. That’s too much information.

Instead, you are going to extract just the most important pieces of information from your model object and create your view using them.

And you won’t just extract them in a one-to-one manner.

Often, you’ll perform some transformations on the data.

Here we took two of the fields from the animal model object and combined them to create a single text containing the genus and species.

That transformation and extraction process is error prone.

But using a view model makes it explicit.

We can clearly see the data being pulled out of the model object and combined so that we can show exactly what we want to, to our users.

And having this be explicit is invaluable because it makes it so easy to test. Whenever we encounter a new flavor of model object that needs to be represented to our users in a different manner, all we need to do is leverage XCTest. Add a new test case, and in that test case create one of our model objects; create from it a view model; and validate that our view model has exactly the data that we want to show to our users to represent that model object.

This is the second major reason we decided to use view models in our zoo application.

What does this mean for your overarching application architecture? Well a big part of building great apps is to take this rich model object graph that exists in your model layer and to represent it to your users, pulling out just the most important pieces of information and showing it to them in a beautiful fashion.

Using a view model can make this so much easier.

The reason is that you can use the following flow: First, for your model objects construct view models.

Finally, you can use XCUI testing to validate the way that your application works in production. I’d like to take a moment to talk about performance. We have told you that previews are just code.

One consequence of this is that you don’t want to run arbitrary operations when your previews are being rendered. You know, you don’t want to calculate the millionth prime.

Similarly, Xcode Previews will call Applicationdid /FinishLaunching /WithOptions.

Instead, make your application scene aware, conform to the UIWindowSceneDelegate, and implement the scene willConnectToOptions method and set up your UI hierarchy there.

And look: This isn’t just beneficial for you, the developer, OK, it’s faster previews as a result. This is also a boon for your users.

When your application launches into the background, it won’t be doing a bunch of extra work.

It’ll just do exactly what it needs to and go back to sleep, avoiding wasting your user’s battery life. Let’s recap here.

You have seen how to write a preview. The preview’s API is part of SwiftUI. It’s really powerful.

And you can use all of SwiftUI when you are writing your previews.

You have seen how to use advanced Xcode workflows, like preview pinning, to keep your state when you are switching between different files.

Finally, you have seen how to use previews not just with SwiftUI and not just with Swift, but with all of the source files that Xcode understands written against UIKit, AppKit, and WatchKit. Well that’s Mastering Xcode Previews. Thank you all for coming. Come see us in the lab.

Looking for something specific? Enter a topic above and jump straight to the good stuff.

An error occurred when submitting your query. Please check your Internet connection and try again.

Источник

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *