[ad_1]
Anatomy of the UICollectionView class
If you happen to’re not acquainted with UICollectionView, I would counsel to get acquainted with this class instantly. They’re the essential constructing blocks for a lot of apps offered by Apple and different third social gathering builders. It is like UITableView on steroids. Here’s a fast intro about how you can work with them via IB and Swift code. 💻
You may need observed that I’ve a love for metallic music. On this tutorial we will construct an Apple Music catalog like look from floor zero utilizing solely the mighty UICollectionView
class. Headers, horizontal and vertical scrolling, round pictures, so mainly nearly all the pieces that you will ever must construct nice person interfaces. 🤘🏻
How one can make a UICollectionView utilizing Interface Builder (IB) in Xcode?
The quick & sincere reply: you should not use IB!
If you happen to nonetheless need to use IB, here’s a actual fast tutorial for completely newcomers:
The principle steps of making your first UICollectionView based mostly display are these:
- Drag a UICollectionView object to your view controller
- Set correct constraints on the gathering view
- Set dataSource & delegate of the gathering view
- Prototype your cell format contained in the controller
- Add constraints to your views contained in the cell
- Set prototype cell class & reuse identifier
- Perform a little coding:
import UIKit
class MyCell: UICollectionViewCell {
@IBOutlet weak var textLabel: UILabel!
}
class ViewController: UIViewController {
@IBOutlet weak var collectionView: UICollectionView!
override func viewDidLayoutSubviews() {
tremendous.viewDidLayoutSubviews()
if let flowLayout = collectionView.collectionViewLayout as? UICollectionViewFlowLayout {
flowLayout.itemSize = CGSize(
width: collectionView.bounds.width,
top: 120
)
}
}
}
extension ViewController: UICollectionViewDataSource {
func numberOfSections(
in collectionView: UICollectionView
) -> Int {
1
}
func collectionView(
_ collectionView: UICollectionView,
numberOfItemsInSection part: Int
) -> Int {
10
}
func collectionView(
_ collectionView: UICollectionView,
cellForItemAt indexPath: IndexPath
) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(
withReuseIdentifier: "MyCell",
for: indexPath
) as! MyCell
cell.textLabel.textual content = String(indexPath.row + 1)
return cell
}
}
extension ViewController: UICollectionViewDelegate {
func collectionView(
_ collectionView: UICollectionView,
didSelectItemAt indexPath: IndexPath
) {
print(indexPath.merchandise + 1)
}
}
In a nutshell, the info supply will present all of the required information about how you can populate the gathering view, and the delegate will deal with person occasions, reminiscent of tapping on a cell. You need to have a transparent understanding concerning the information supply and delegate strategies, so be happy to play with them for a short while. ⌨️
How one can setup a UICollectionView based mostly display programmatically?
As you may need observed cells are the core elements of a group view. They’re derived from reusable views, which means that in case you have an inventory of 1000 components, there will not be a thousand cells created for each ingredient, however only some that fills the dimensions of the display and while you scroll down the record this stuff are going to be reused to show your components. That is solely due to reminiscence issues, so not like UIScrollView the UICollectionView (and UITableView) class is a very good and environment friendly one, however that is additionally the rationale why you need to put together (reset the contents of) the cell each time earlier than you show your precise information. 😉
Initialization can also be dealt with by the system, but it surely’s price to say that if you’re working with Interface Builder, you need to do your customization contained in the awakeFromNib
methodology, however if you’re utilizing code, init(body:)
is your house.
import UIKit
class MyCell: UICollectionViewCell {
weak var textLabel: UILabel!
override init(body: CGRect) {
tremendous.init(body: body)
let textLabel = UILabel(body: .zero)
textLabel.translatesAutoresizingMaskIntoConstraints = false
contentView.addSubview(textLabel)
NSLayoutConstraint.activate([
textLabel.topAnchor.constraint(
equalTo: contentView.topAnchor
),
textLabel.bottomAnchor.constraint(
equalTo: contentView.bottomAnchor
),
textLabel.leadingAnchor.constraint(
equalTo: contentView.leadingAnchor
),
textLabel.trailingAnchor.constraint(
equalTo: contentView.trailingAnchor
),
])
self.textLabel = textLabel
contentView.backgroundColor = .lightGray
textLabel.textAlignment = .heart
}
required init?(coder aDecoder: NSCoder) {
tremendous.init(coder: aDecoder)
fatalError("Interface Builder will not be supported!")
}
override func awakeFromNib() {
tremendous.awakeFromNib()
fatalError("Interface Builder will not be supported!")
}
override func prepareForReuse() {
tremendous.prepareForReuse()
textLabel.textual content = nil
}
}
Subsequent we’ve to implement the view controller which is chargeable for managing the gathering view, we’re not utilizing IB so we’ve to create it manually by utilizing Auto Structure anchors – like for the textLabel
within the cell – contained in the loadView
methodology. After the view hierarchy is able to rock, we additionally set the info supply and delegate plus register our cell class for additional reuse. Observe that that is completed robotically by the system if you’re utilizing IB, however should you choose code you need to do it by calling the right registration methodology. You’ll be able to register each nibs and lessons.
import UIKit
class ViewController: UIViewController {
weak var collectionView: UICollectionView!
override func loadView() {
tremendous.loadView()
let collectionView = UICollectionView(
body: .zero,
collectionViewLayout: UICollectionViewFlowLayout()
)
collectionView.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(collectionView)
NSLayoutConstraint.activate([
collectionView.topAnchor.constraint(
equalTo: view.topAnchor
),
collectionView.bottomAnchor.constraint(
equalTo: view.bottomAnchor
),
collectionView.leadingAnchor.constraint(
equalTo: view.leadingAnchor
),
collectionView.trailingAnchor.constraint(
equalTo: view.trailingAnchor
),
])
self.collectionView = collectionView
}
override func viewDidLoad() {
tremendous.viewDidLoad()
collectionView.backgroundColor = .white
collectionView.dataSource = self
collectionView.delegate = self
collectionView.register(
MyCell.self,
forCellWithReuseIdentifier: "MyCell"
)
}
}
extension ViewController: UICollectionViewDataSource {
func numberOfSections(
in collectionView: UICollectionView
) -> Int {
1
}
func collectionView(
_ collectionView: UICollectionView,
numberOfItemsInSection part: Int
) -> Int {
10
}
func collectionView(
_ collectionView: UICollectionView,
cellForItemAt indexPath: IndexPath
) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(
withReuseIdentifier: "MyCell",
for: indexPath
) as! MyCell
cell.textLabel.textual content = String(indexPath.row + 1)
return cell
}
}
extension ViewController: UICollectionViewDelegate {
func collectionView(
_ collectionView: UICollectionView,
didSelectItemAt indexPath: IndexPath
) {
print(indexPath.row + 1)
}
}
extension ViewController: UICollectionViewDelegateFlowLayout {
func collectionView(
_ collectionView: UICollectionView,
format collectionViewLayout: UICollectionViewLayout,
sizeForItemAt indexPath: IndexPath
) -> CGSize {
.init(
width: collectionView.bounds.measurement.width - 16,
top: 120
)
}
func collectionView(
_ collectionView: UICollectionView,
format collectionViewLayout: UICollectionViewLayout,
minimumLineSpacingForSectionAt part: Int
) -> CGFloat {
8
}
func collectionView(
_ collectionView: UICollectionView,
format collectionViewLayout: UICollectionViewLayout,
minimumInteritemSpacingForSectionAt part: Int
) -> CGFloat {
0
}
func collectionView(
_ collectionView: UICollectionView,
format collectionViewLayout: UICollectionViewLayout,
insetForSectionAt part: Int
) -> UIEdgeInsets {
.init(prime: 8, left: 8, backside: 8, proper: 8)
}
}
This time you need to pay some consideration on the circulation format delegate strategies. You should use these strategies to supply metrics for the format system. The circulation format will show all of the cells based mostly on these numbers and sizes. sizeForItemAt is chargeable for the cell measurement, minimumInteritemSpacingForSectionAt
is the horizontal padding, minimumLineSpacingForSectionAt
is the vertical padding, and insetForSectionAt
is for the margin of the gathering view part.
Utilizing supplementary components (part headers and footers)
So on this part I will each use storyboards, nibs and a few Swift code. That is my common method for just a few causes. Though I really like making constraints from code, most individuals choose visible editors, so all of the cells are created inside nibs. Why nibs? As a result of in case you have a number of assortment views that is “nearly” the one good method to share cells between them.
You’ll be able to create part footers precisely the identical method as you do headers, in order that’s why this time I am solely going to deal with headers, as a result of actually you solely have to vary one phrase as a way to use footers. ⚽️
You simply must create two xib information, one for the cell and one for the header. Please observe that you could possibly use the very same assortment view cell to show content material within the part header, however this can be a demo so let’s simply go along with two distinct gadgets. You do not even must set the reuse identifier from IB, as a result of we’ve to register our reusable views contained in the supply code, so simply set the cell class and join your shops.
Cell and supplementary ingredient registration is barely totally different for nibs.
let cellNib = UINib(nibName: "Cell", bundle: nil)
self.collectionView.register(
cellNib,
forCellWithReuseIdentifier: "Cell"
)
let sectionNib = UINib(nibName: "Part", bundle: nil)
self.collectionView.register(
sectionNib,
forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader,
withReuseIdentifier: "Part"
)
Implementing the info supply for the part header seems to be like this.
func collectionView(
_ collectionView: UICollectionView,
viewForSupplementaryElementOfKind type: String,
at indexPath: IndexPath
) -> UICollectionReusableView {
guard type == UICollectionView.elementKindSectionHeader else {
return UICollectionReusableView()
}
let view = collectionView.dequeueReusableSupplementaryView(
ofKind: type,
withReuseIdentifier: "Part",
for: indexPath
) as! Part
view.textLabel.textual content = String(indexPath.part + 1)
return view
}
Offering the dimensions for the circulation format delegate can also be fairly easy, nevertheless typically I do not actually get the naming conventions by Apple. As soon as you need to change a sort, and the opposite time there are precise strategies for particular varieties. 🤷♂️
func collectionView(
_ collectionView: UICollectionView,
format collectionViewLayout: UICollectionViewLayout,
referenceSizeForHeaderInSection part: Int
) -> CGSize {
.init(
width: collectionView.bounds.measurement.width,
top: 64
)
}
Ranging from iOS9 part headers and footers may be pinned to the highest or backside of the seen bounds of the gathering view.
if let flowLayout = self.collectionView.collectionViewLayout as? UICollectionViewFlowLayout {
flowLayout.sectionHeadersPinToVisibleBounds = true
}
That is it, now you know the way to construct fundamental layouts with assortment view.
What about complicated instances, like utilizing a number of sorts of cells in the identical assortment view? Issues can get fairly messy with index paths, in order that’s why I re-invented one thing higher based mostly on a way how you can construct superior person interfaces with assortment views showcased by Apple again at WWDC 2014.
My CollectionView based mostly UI framework
Now you realize the fundamentals, so why do not we get straight to the purpose? I am going to present you my greatest observe of constructing nice person interfaces by utilizing my MVVM structure based mostly CollectionView micro framework.
CollectionView + ViewModel sample = ❤️ .
I am going to clarify the elements actual fast and after that you will discover ways to use them to construct up the Apple music-ish format that I used to be speaking about at first. 🎶
Grid system
The primary drawback with assortment views is the dimensions calculation. It’s a must to present the dimensions (width & top) for every cell inside your assortment view.
- if all the pieces has a hard and fast measurement inside your assortment view, you possibly can simply set the dimensions properties on the circulation format itself
- should you want dynamic sizes per merchandise, you possibly can implement the circulation format delegate aka. UICollectionViewDelegateFlowLayout (why is the delegate phrase in the midst of the title???) and return the precise sizes for the format system
- should you want much more management you possibly can create a brand new format subclass derived from CollectionView(Stream)Structure and do all the dimensions calculations there
Thats good, however nonetheless you need to mess with index paths, trait collections, frames and lots of extra as a way to have a easy 2, 4, n column format that adapts on each gadget. That is the rationale why I’ve created a very fundamental grid system for measurement calculation. With my grid class you possibly can simply set the variety of columns and get again the dimensions for x quantity of columns, “similar to” in internet based mostly css grid programs. 🕸
Cell reuse
Registering and reusing cells ought to and may be automated in a sort protected method. You simply need to use the cell, and also you should not care about reuse identifiers and cell registration in any respect. I’ve made a pair helper strategies as a way to make the progress extra nice. Reuse identifiers are derived from the title of the cell lessons, so that you dont’t have to fret about anymore. It is a observe that a lot of the builders use.
View mannequin
view mannequin = cell (view) + information (mannequin)
Filling up “template” cell with actual information ought to be the duty of a view mannequin. That is the place MVVM comes into play. I’ve made a generic base view mannequin class, that you need to subclass. With the assistance of a protocol, you should use varied cells in a single assortment view with out going loopy of the row & part calculations and you may deal with one easy process: connecting view with fashions. 😛
Part
part = header + footer + cells
I am making an attempt to emphasise that you do not need to mess with index paths, you simply need to put your information collectively and that is it. Prior to now I’ve struggled greater than sufficient with “pointless index path math”, so I’ve made the part object as a easy container to wrap headers, footers and all of the gadgets inside the part. The consequence? Generic information supply class that can be utilized with a number of cells with none row or part index calculations. 👏👏👏
Supply
So as a way to make all of the issues I’ve talked about above work, I wanted to implement the gathering view delegate, information supply, and circulation format delegate strategies. That is how my supply class was born. The whole lot is applied right here, and I am utilizing sections, view fashions the grid system to construct up assortment views. However hey, sufficient from this idea, let’s have a look at it in observe. 👓
CollectionView framework instance software
How one can make a any record or grid format trouble free? Nicely, as a primary step simply add my CollectionView framework as a dependency. Don’t be concerned you will not remorse it, plus it helps Xcode 11 already, so you should use the Swift Package deal Supervisor, straight from the file menu to combine this package deal.
Tip: simply add the @_exported import CollectionView
line within the AppDelegate file, then you definately I haven’t got to fret about importing the framework file-by-file.
Step 1. Make the cell.
This step is similar with the common setup, besides that your cell must be a subclass of my Cell class. Add your individual cell and do all the pieces as you’d do usually.
import UIKit
class AlbumCell: Cell {
@IBOutlet weak var textLabel: UILabel!
@IBOutlet weak var detailTextLabel: UILabel!
@IBOutlet weak var imageView: UIImageView!
override func awakeFromNib() {
tremendous.awakeFromNib()
self.textLabel.font = UIFont.systemFont(ofSize: 12, weight: .daring)
self.textLabel.textColor = .black
self.detailTextLabel.font = UIFont.systemFont(ofSize: 12, weight: .daring)
self.detailTextLabel.textColor = .darkGray
self.imageView.layer.cornerRadius = 8
self.imageView.layer.masksToBounds = true
}
override func reset() {
tremendous.reset()
self.textLabel.textual content = nil
self.detailTextLabel.textual content = nil
self.imageView.picture = nil
}
}
Step 2. Make a mannequin
Simply choose a mannequin object. It may be something, however my method is to make a brand new struct or class with a Mannequin suffix. This manner I do know that fashions are referencing the gathering view fashions inside my reusable elements folder.
import Basis
struct AlbumModel {
let artist: String
let title: String
let picture: String
}
Step 3. Make the view mannequin.
Now as an alternative of configuring the cell contained in the delegate, or in a configure methodology someplace, let’s make an actual view mannequin for the cell & the info mannequin that is going to be represented through the view.
import UIKit
class AlbumViewModel: ViewModel<AlbumCell, AlbumModel> {
override func updateView() {
self.view?.textLabel.textual content = self.mannequin.artist
self.view?.detailTextLabel.textual content = self.mannequin.title
self.view?.imageView.picture = UIImage(named: self.mannequin.picture)
}
override func measurement(grid: Grid) -> CGSize {
if
(self.collectionView.traitCollection.userInterfaceIdiom == .telephone &&
self.collectionView.traitCollection.verticalSizeClass == .compact) ||
self.collectionView?.traitCollection.userInterfaceIdiom == .pad
{
return grid.measurement(
for: self.collectionView,
ratio: 1.2,
gadgets: grid.columns / 4,
gaps: grid.columns - 1
)
}
if grid.columns == 1 {
return grid.measurement(for: self.collectionView, ratio: 1.1)
}
return grid.measurement(
for: self.collectionView,
ratio: 1.2,
gadgets: grid.columns / 2,
gaps: grid.columns - 1
)
}
}
Step 4. Setup your information supply.
Now, use your actual information and populate your assortment view utilizing the view fashions.
let grid = Grid(columns: 1, margin: UIEdgeInsets(all: 8))
self.collectionView.supply = .init(grid: grid, [
[
HeaderViewModel(.init(title: "Albums"))
AlbumViewModel(self.album)
],
])
self.collectionView.reloadData()
Step 5. 🍺🤘🏻🎸
Congratulations you are completed along with your first assortment view. With just some traces of code you’ve a ROCK SOLID code that may enable you to out in a lot of the conditions! 😎
That is simply the tip of the iceberg! 🚢
Horizontal scrolling inside vertical scrolling
What if we make a cell that accommodates a group view and we use the identical methodology like above? A set view containing a group view… UICollectionViewception!!! 😂
It is fully attainable, and very easy to do, the info that feeds the view mannequin will probably be a group view supply object, and also you’re completed. Easy, magical and tremendous good to implement, additionally included within the instance app.
Sections with artists & round pictures
A number of sections? No drawback, round pictures? That is additionally a bit of cake, should you had learn my earlier tutorial about round assortment view cells, you may know how you can do it, however please take a look at the supply code from GitLab and see it for your self in motion.
Callbacks and actions
Person occasions may be dealt with very straightforward, as a result of view fashions can have delegates or callback blocks, it solely is dependent upon you which ones one you like. The instance accommodates an onSelect handler, which is tremendous good and built-in to the framework. 😎
Dynamic cell sizing re-imagined
I additionally had a tutorial about assortment view self sizing cell help, however to be sincere I am not an enormous fan of Apple’s official methodology. After I’ve made the grid system and began utilizing view fashions, it was less difficult to calculate cell heights on my own, with about 2 traces of additional code. I imagine that is price it, as a result of self sizing cells are just a little buggy if it involves auto rotation.
Rotation help, adaptivity
Don’t be concerned about that an excessive amount of, you possibly can merely change the grid or test trait collections contained in the view mannequin if you need. I would say nearly all the pieces may be completed proper out of the field. My assortment view micro framework is only a light-weight wrapper across the official assortment view APIs. That is the great thing about it, be happy to do no matter you need and use it in a method that YOU personally choose. 📦
Now go, seize the pattern code and hearken to some metallic! 🤘🏻
What if I informed you… yet another factor: SwiftUI
These are some unique quotes of mine again from April, 2018:
If you happen to like this methodology that is cool, however what if I informed you that there’s extra? Do you need to use the identical sample in all places? I imply on iOS, tvOS, macOS and even watchOS. Carried out deal! I’ve created all the pieces contained in the CoreKit framework. UITableViews, WKInterfaceTables are supported as effectively.
Nicely, I am a visionary, however SwiftUI was late 1 yr, it arrived in 2019:
I actually imagine that Apple this yr will method the subsequent technology UIKit / AppKit / UXKit frameworks (written in Swift after all) considerably like this. I am not speaking concerning the view mannequin sample, however about the identical API on each platform considering. Anyway, who is aware of this for sue, we’ll see… #wwdc18 🤔
If somebody from Apple reads this, please clarify me why the hell is SwiftUI nonetheless an abstraction layer above UIKit/ AppKit as an alternative of a refactored AppleKit UI framework that lastly unifies each single API? For actual, why? Nonetheless do not get it. 🤷♂️
Anyway, we’re entering into to the identical path guys, year-by-year I delete increasingly self-written “Third-party” code, so that you’re doing nice progress there! 🍎
[ad_2]