Snapkit swift что это
Русские Блоги
Swift iOS:SnapKit
Технология макета по умолчанию, предоставляемая iOS, мощная и глупая. К счастью, есть пакет SnapKit, который упрощает чтение и изменение макета.
Предполагая, что на UIViewController должны быть размещены две метки, требования следующие:
Ты можешь это сделать:
Интеллектуальная рекомендация
Используйте шаблон состояния вместо if else
Большинство разработчиков все еще используютif elseСтруктура процесса, виделиjdonизbanqСтатья написана Большим Братом, используяcommand,aopЗамена шаблонаif elseСтруктура процесса. Я не совсем понял эт.
Рыба образования, средняя школа закончила в учебном класс, как найти первую работу.
Self-брат Я девять ноль, теперь занимается разработкой веб-конца Java. Некоторое понимание и восприятие учебных курсов. Учебное заведение является ямой, дорога, что вы уже прошли, только вы знаете, дл.
Синглтон паттерн в питоне
Java Counce Collection
TRUEEWAP основан на реализации красных навигаций. Это отображение отсортировано в соответствии с его природооформленным порядком или отсортировано в соответствии с компаратором, предусмотренным при со.
Вам также может понравиться
1. Связанные классы и методы: java.lang.reflect.Proxy, Прокси предоставляет статические методы для создания динамических прокси-классов и экземпляров. newProxyInstance() Возвращает экземпляр прокси-кл.
Юля: Об изменениях в Array 1.0
Версии до 1.0, например 0.2-0.6, Но теперь 1.0 это сообщит об ошибке. Это использование претерпело серьезные изменения! такие как: Это можно считать серьезным изменением.
студия Android генерирует статическую библиотеку jni
Android Сяобай, который только что вошел в общество, описывает, как использовать студию Android для создания статической библиотеки jni. 1. Подготовка: Сначала установите ndk, сначала сами Baidu, позж.
Nginx 502 раствор
Общие решения Nginx 502 Bad Gateway следующие: Nginx 502 Ошибка 1: Количество сайтов велико, а количество PHP-CGI мало. Для этой 502 ошибки просто увеличивайте количество процессов PHP-CGI. В частност.
Java вызывает SMS-интерфейс WebService
About this How-to
Who this How-to is for
What you will learn & Get
Let’s GO
Install SnapKit
We can install SnapKit via dependencies manages (Cocoapods, Carthage) or Embedded framework but now i’ll show you how to install SnapKit by Cocoapods. If this your first time using cocoapods just open Terminal and typing
Go to the your project directory from
Make new Podfile for your Xcode project
Open Podfile in Text Editor or open directly from terminal
Integrate SnapKit into your Xcode project, specify it in your Podfile
Then, run the following command for install SnapKit
Success!! Now SnapKit integrated with your project, double click on yourproject.xcworkspace file to open Xcode
Usage
First thing you need to import SnapKit framework to your view controller by import statement
Alignment & Positioning
Let’s say we want to layout some UIButton that is constrained to it’s superview at the right bottom edges with 20pts.
That is first example in this How-To, I want to explain the view attribute in SnapKit, it similar with NSLayoutAttribute you can align your custom layout easily.
This important method is snp_makeConstraints it will make constraints to your view.
In the screen you can see custom navigation bar, this nav bar has UIView for background and UILabel for title. We want to stick custom nav bar on top of superview with height 64pts and width equal to superview and title label is embedded inside a UIView(Navigation bar) center. Try …
You would know how to alignment and positioning already, then i’ll move on composition by SnapKit.
Composition
SnapKit can do easier way to create multiple constrains at the same time.
Center : You can align subview to center refer by superview.
Done! In composition example i hope it will help you understand how to use edges, size, center.
snp_updateConstraints : If you want to updating the constant value of the constraint you can use this method.
snp_remakeConstraints : this method is similar to snp_makeConstraint, but will first remove all existing constraints installed, code below will move my button to bottom-left of superview and resize to 44pts.
Constraints Priority
In the Auto layout sometime your view should have priority for decision about adjust the position, size and other.
you can add priority on to the end of a constraint chain.
It very easy to solve that problem and flexible to change left-spacing of all element by Global constant in Swift.
The example project is ready on Github, you can download here : Download
Hopefully, I think you will understand how to use SnapKit for solving auto layout problem. SnapKit also make your code to readable and decreases time to develop user interface as well.
Finally, what’s your opinion about SnapKit? You can leave your comment below. Let’s share idea!
Use SnapKit, Swift framework, easily
Apr 26, 2016 · 4 min read
In this short article, I’ll introduce SnapKit.
SnapKit is a lightweight Swift framework abstraction of Apple Auto Layout constraint-based layout engine with more readable and understandable syntax.
It will be hard to understand programmatic contraints with NSLayoutConstraint class who provide hard syntax and operators.
This time is over since SnapKit was out and I’ll show you how it’s easy to use it.
Setup
You can install it with Cocoapods, Carthage or embed framework. SnapKit is available for OS X and iOS and support iOS7+ or OS X 10.9+ (Swift 2+ and Xcode 7+)
Please r e fer to SnapKit Github page for more precision about the installation.
Beginning
I started with single view application, and opened the ViewController class
First thing to do: Import SnapKit to the controller
I create a simple label and add it to the controller’s view, with “HELLO” text
It’s totally normal because of CGRect.zero on label. Just add sizeToFit() method will show you the label on left top of the view but it’s not the result we expected.
It’s simple, we just want our label centered and 25pt below the top of the superview.
This is time to do some SnapKit magic.
SnapKit in use
We will call the snp_makeContraint() method which will allow us to add wanted contraints.
It’s a block which give use one variable we named make. This is THE only thing you can care of. Thank’s to that, we will add our contraints easily.
On make object, we have access a lot of thing, included the top object. Top represent the top of our element. After that, equalTo(25) who represent value of the contraint we made.
At this point we have the result expected, we can center our element now
Just below our first contraint, we add another line.
This means that our element will be centered on X axis of the parent element.
There is mutiple possibilities to make this contraints and I’ll show you some:
For more contraints, and ways to make this contraints
Animate contraints
Now, I will show you how to made an animation on a SnapKit contraint.
For exemple we will take our previous code to make an incrementation of 25pt on our top contraint label.
We need to make an reference to access contraint on our controller.
I added an optional variable to my controller named topLabelContraint kind of Contraint (provided by SnapKit)
To keep the reference of our top contraint we use contraint variable of top object and assign it to topLabelContraint.
Now we will can change dynamically the value of the top contraint and make some nice animations.
I added the animation on viewDidAppear just to have time to see what’s going on.
If you do that, the constraint will be updated with your value, but there is no animations here with this code.
You’ve got a little preview of SnapKit possibilities, this make a difference if you are not comfortable with programatic constraints who are needed for complex views who can’t be done with storyboard.
How to Use SnapKit to Write Constraints Programmatically for iOS Apps
When I first started building apps with Xcode, I thought Storyboards were magic. Dragging and dropping subviews into place was so simple, I never understood how people built views without them.
Eventually, I decided that to become a “master programmer,” I would need to learn how to construct views programmatically. One problem, writing constraints in code is a pain.
That’s a horizontal constraint that will center a subview on the X axis of its superview. Not so easy to read not to mention writing that for every constraint gets old fast. Still, I wanted to ditch storyboards so I searched for an alternative. That’s when I found SnapKit.
SnapKit has a clear and concise API that makes writing constraints in the code a breeze. I’m going to go through a few really basic examples of what can be done in SnapKit.
Getting started
Make sure you download SnapKit in your project. I use Cocoapods for 3rd party libraries.
Laying out a subview in its superview
First off I’ll pin a subview to the edges of its superview:
This will set constraints for the top, bottom, left, and right edges of the subview to the corresponding edges of its superview with a constant of 0.
Notice that I add the subview to the superview before I setting the subview’s constraints. If you write constraints for views that aren’t already added to the superview, it will throw a fatal runtime error when the view loads.
The SnapKit syntax is already a lot more readable than the standard library but it can be shortened. SnapKit provides an even more concise way to constrain a view to the edges of its superview:
This will layout my subview the same way as the code above, but with one line instead of four.
I can also constrain the size of my subview. Below, I’m going to set the height and width of the subview and set it to the center of its superview:
That example is pretty simple, but I repeated myself a lot. When setting constraints that have the same values, SnapKit allows me to chain constraints together like so:
This block will result in the same constraints as the one above. Just another way SnapKit helps to write cleaner code.
Laying out subviews relative to each other
When adding many subviews to a single view, it’s likely that you’ll want to layout subviews in relation to each other. In this example, I will:
I can access any constraint of a view’s layout by adding snp as seen above.
An offset can be appended at the end of any equalTo() to change the constant of that constraint. Now subview2 will have a constant of 50 on its left constraint.
Updating and animating constraints
If you want your app to be the #NextBigThing everyone knows you’ll need to add a little flair! SnapKit provides a way to easily update constraints to create dynamic views.
Updating a constraint with SnapKit is almost identical to adding a new one. Here, I’ll update the constraint for subview1 from the previous example by changing the left edge constraint’s constant from 0 to 50:
And that’s it! My subview will update to the new constraints when the code block is run.
Now I’ll add an animation to smooth out the transition. If you’ve ever animated a view before, this syntax will be familiar:
When animating updates on my constraints, I need to call layoutIfNeeded() on the subview’s parent. If I’m animating more than one view at once, I will need to call layoutIfNeeded() on the subview’s closest common superview.
updateConstraints() can only update existing constraints. Attempting to update a constraint that isn’t already in place will result in a fatal run time error.
You can also use deactivate() to remove a constraint. Below I create, set, and them remove a constraint using deactivate() :
You can also animate the removal of a constraint by deactivating it inside of an animation block.
So now you are a master of writing constraints programmatically. Storyboards seem like a joke now and there’s no reason to ever go back to them, right?
Not really. Storyboards and nibs are still the fastest way to put together a view controller, and, if you are working with non-developers, they are the best way to show what the app will look like without sending a beta version.
Personally, I use both. In the last app I built, I added constraints both in code with SnapKit and using Auto Layout on storyboards and nibs, sometimes on the same view. In the end, you’ll have to decide which works best for the view you are building.
Thanks so much for reading! If you liked this story, follow me on Twitter where I post articles about product management, engineering, and design.
Русские Блоги
Руководство по роумингу SnapKit
В дополнение к всестороннему обновлению всей экосистемы на WWDC в этом году, официальный выпуск Apple сопровождался Swift 3.0, который был выпущен в то же время. Если вы не решались переключить основной язык проекта на Swift год назад, возможно, позже Официальный выпуск Swift 3.0 постепенно рассеет ваши опасения по этому поводу. С быстрым развитием Swift за последние два года и после того, как он стал открытым исходным кодом, постоянный вклад гордости и сообщества открытого исходного кода еще больше похож на выброс. Конечно, за исключением Платформа iOS, Swift также поддерживает Linux. Язык Swift дает мне более интуитивное ощущение, что мне наконец-то не нужно писать подробный стиль кода, подобный Object-C. Приятно назвать краткий и легкий для чтения Swift. На самом деле, особых ожиданий нет, но если есть функция Async-Style на таком языке, как C #, это было бы здорово. Конечно, она выпущена из официальногоДорожная карта SwiftВидно, что в версии 3.0 не так много серьезных нововведений, и основным направлением является устранение влияния языка C. Если у Swift все еще есть проблемы с производительностью до версии 3.0 (отсутствие зрелых сторонних фреймворков), успейте увидеть Глядя на ресурсы, связанные с github, возможно, сейчас хорошее время для начала.
Если вы помните строки ограничений в StoryBoard, то вы также должны помнить формулировки констант. SnapKit делает следующее: позволяет писать ограничения в цепочке синтаксической инкапсуляции:
Конечно, не о чем беспокоиться, если вы использовали Masonry, но SnapKit более гибкий, чем Masonry (подробности будут объяснены позже):
установка
Перед установкой вам необходимо обратить внимание на конфигурацию среды, требуемую SnapKit:
Установите SnapKit с помощью Carthage:
При установке укажите последнюю выпущенную версию. Создайте ссылку с помощью команды обновления carthage и найдите созданную ссылку в корневом каталоге проекта:
File, а затем интегрируйте файл в:
В опциях введите в код проекта:
Если компиляция прошла успешно, установка завершена. Конечно, если вы больше привыкли к CocoaPod или другим методам установки, обратитесь кОфициальный документ.
Основное использование
Поскольку дизайнерская идея SnapKit продолжает OC-версию Masonry, она просто меняется на язык реализации Swift.Если вы хорошо знакомы с Masonry, их базовое использование похоже.
Сначала рассмотрим базовый пример, мы сначала попытаемся разместить GrayBox в макете пользовательского интерфейса:
Базовое написание не сильно отличается от Masonry, но в SnapKit, если несколько значений атрибутов одинаковы, вы можете объединить атрибуты представления для повышения их читабельности. Как и в приведенном выше письме, существует более простая реализация:
Передайте ‘в SnapKitsnp_makeConstraints‘Добавьте ограничения к элементу. Ограничения в основном делятся на поля, ширину, высоту, расстояния в верхнем левом и нижнем правом углу и базовые линии. Конечно, добавление ограничений также можно исправить. Метод коррекции включает в себя коррекцию смещения [‘inset、offset’] И коррекция увеличения [multipliedBy].
Таблица сравнения атрибутов, поддерживаемых SnapKit и NSLayoutAttrubute, выглядит следующим образом:
Среди них ведущее и левое, конечное и правое при нормальных обстоятельствах эквивалентны, но когда некоторые макеты расположены справа налево (например, арабский), они будут перевернуты. Другими словами, в большинстве случаев они фактически эквивалентны. Взаимодействие с другими людьми
Обычно существует три типа модифицированного синтаксиса ограничений, которые в точности такие же, как и в масонстве.
.lessThanOrEqualTo: меньше или равно
.greaterThanOrEqualTo: больше или равно
Что касается базового использования,Официальные документы и примерыЭто очень подробно описано здесь, и я не буду его здесь вводить. Сосредоточьтесь на других редких случаях использования масонства.
Коррекция увеличения
В макете у нас есть два квадратных цветных блока. Теперь мы используем метод коррекции увеличения. Используйте метод коррекции увеличения, чтобы уменьшить оранжевый вид до половины серого, как показано ниже:
Может быть использованmultipliedByдостичь:
Обратите внимание, что я должен сказать этоmultipliedByметод,В настоящее время требуется только размер оранжевого представления, который является свойством Size, а значение, которое может принимать этот метод, можно найти из его определения. Существует несколько типов значений:
То же самое и с DividedBy.
Ссылка на ограничение
В ежедневном макете мы можем обновлять значение одного и того же ограничения в нескольких местах. Для этого требуется возможность изменять, удалять, заменять и другие операции с существующими определенными ограничениями. SnapKit может присвоить результат ограничения локальной переменной или Атрибут класса, а затем работать со ссылкой на это ограничение.Это значительно упрощает стоимость работы с ограничением, обеспечивая его гибкость.
На странице у нас есть оранжевый вид, 100 сверху, по центру по горизонтали.При нажатии кнопки страницы ограничение снимается, и эффект выглядит следующим образом:
Реализация очень проста:
Во-первых, что такое объект ограничения topConstraint, при добавлении ограничения к оранжевому представлению он относится к ограничению верхнего интервала SuperView. Когда нажимается кнопка для удаления кнопки ограничения, запускается операция удаления:
Когда удаление запускается, операция завершается вызовом метода uninstall для topConstraint. После завершения удаления, если вы обновите ограничения, например, измените расстояние от оранжевого представления до верха со 100 до 200 пикселей. Просто используйте updateOffset (200), Конечно, поскольку перед этой операцией использовалось удаление, ограничение было недоступно. Вам нужно активировать его с помощью Activ перед вызовом метода updateOffset, иначе это не даст никакого эффекта.
Приоритет ограничения
Когда для одного и того же элемента установлено несколько ограничений, можно определить приоритет ограничений. Таким образом, при конфликте ограничений ограничения с более высоким приоритетом переопределяют ограничения с более низким приоритетом.
priorityLow (): установите низкий приоритет, приоритет 250
priorityMedium (): установите средний приоритет, приоритет 500 (приоритет по умолчанию)
priorityHigh (): установить высокий приоритет, приоритет 750
Синтаксис приоритетного использования обычно помещается в конец цепочки ограничений, например:
Чтобы узнать об ограничении места, обратитесь к официальной демонстрации или этой демонстрации для использованияИсходный код на github.Я не буду здесь вдаваться в подробности.