Self sizing table view cells based on ui stack view content - ios

i want to create cells with stack view in it. For different cells there would be different amount of arranged subviews in stack view.
Currently i create something like this but self sizing isn't working.
Table view initialization:
let tableView: UITableView = {
let tableView = UITableView()
tableView.rowHeight = UITableView.automaticDimension
tableView.estimatedRowHeight = 200
return tableView
}()
Table view cell:
import UIKit
final class CustomTableViewCell: UITableViewCell {
private let stackView: UIStackView = {
let stackView = UIStackView()
stackView.axis = .vertical
stackView.spacing = 8
stackView.distribution = .equalSpacing
stackView.alignment = .fill
return stackView
}()
// initializations...
private func setup() {
backgroundColor = .green
addSubviewsWithConstraints([stackView])
NSLayoutConstraint.activate([
stackView.leadingAnchor.constraint(equalTo: leadingAnchor),
stackView.trailingAnchor.constraint(equalTo: trailingAnchor),
stackView.topAnchor.constraint(equalTo: topAnchor),
stackView.bottomAnchor.constraint(equalTo: bottomAnchor)
])
stackView.addArrangedSubviews([CustomView(), CustomView()])
// custom views will be added later depends on model
}
}
Custom view:
final class CustomView: UIView {
private let iconImageView: UIImageView = {
let imageView = UIImageView()
imageView.image = UIImage(systemName: "heart.fill")
return imageView
}()
//MARK: - Override
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
private override init(frame: CGRect) {
super.init(frame: frame)
setup()
}
private func setup() {
addSubviewsWithConstraints([iconImageView])
NSLayoutConstraint.activate([
iconImageView.topAnchor.constraint(equalTo: topAnchor, constant: 6),
iconImageView.leadingAnchor.constraint(equalTo: leadingAnchor, constant: 6),
iconImageView.heightAnchor.constraint(equalToConstant: 80),
iconImageView.widthAnchor.constraint(equalToConstant: 80)
])
}
}
To add subviews i'm using custom extension to uiview:
func addSubviewWithConstraints(_ view: UIView) {
view.translatesAutoresizingMaskIntoConstraints = false
addSubview(view)
}
func addSubviewsWithConstraints(_ views: [UIView]) {
views.forEach {
addSubviewWithConstraints($0)
}
}
Result looks like this (using 2 cells with 2 custom views in stack views):

Your addSubviewsWithConstraint is adding views as a subview of the cell not as a subview of the contentView. Cells use the contentView for self sizing. As addSubviewsWithConstraint is an extension of UIView you should be able to do the following anywhere you want to add a subview to a cell.
contentView.addSubviewWithConstraints(...)
Just another thing that may be useful is that you can shorten your functions down by using variadic arguments like so:
func addSubviewWithConstraints(_ views: UIView...) {
views.forEach {
addSubviewWithConstraints($0)
}
}
Usage
addSubviewWithConstraints(mySubview)
addSubviewWithConstraints(mySubview, mySubview2, mySubview3)

Related

How to put UIView inside UIScrollView in Swift?

I am trying to add a UIView into a UIScrollView without storyboard. I made some code with the given two files(CalcTypeView.siwft and CalcTypeViewController.swift) as below. However, as shown in the screenshot image, I can see the UIScrollView(gray color) while UIView(red color) does not appear on the screen. What should I do more with these code to make UIView appear? (I've already found many example code using single UIViewController, but what I want is UIView + UIViewController form to maintain MVC pattern)
1. CalcTypeView.swift
import UIKit
final class CalcTypeView: UIView {
private let scrollView: UIScrollView = {
let view = UIScrollView()
view.translatesAutoresizingMaskIntoConstraints = false
view.backgroundColor = .gray
view.showsVerticalScrollIndicator = true
return view
}()
private let contentView1: UIView = {
let view = UIView()
view.translatesAutoresizingMaskIntoConstraints = false
view.backgroundColor = .red
view.clipsToBounds = true
view.layer.cornerRadius = 10
return view
}()
override init(frame: CGRect) {
super.init(frame: frame)
setupScrollView()
setupContentView()
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
private func setupScrollView() {
self.addSubview(scrollView)
NSLayoutConstraint.activate([
scrollView.centerXAnchor.constraint(equalTo: self.centerXAnchor),
scrollView.widthAnchor.constraint(equalTo: self.widthAnchor),
scrollView.topAnchor.constraint(equalTo: self.layoutMarginsGuide.topAnchor),
scrollView.bottomAnchor.constraint(equalTo: self.layoutMarginsGuide.bottomAnchor),
])
}
private func setupContentView() {
scrollView.addSubview(contentView1)
NSLayoutConstraint.activate([
contentView1.leadingAnchor.constraint(equalTo: scrollView.contentLayoutGuide.leadingAnchor, constant: 20),
contentView1.trailingAnchor.constraint(equalTo: scrollView.contentLayoutGuide.trailingAnchor, constant: -20),
contentView1.topAnchor.constraint(equalTo: scrollView.contentLayoutGuide.topAnchor, constant: 20),
contentView1.bottomAnchor.constraint(equalTo: scrollView.contentLayoutGuide.bottomAnchor, constant: -20),
])
}
}
2. CalcTypeViewController.swift
import UIKit
final class CalcTypeViewController: UIViewController {
private let calcTypeView = CalcTypeView()
override func viewDidLoad() {
super.viewDidLoad()
setupNavBar()
setupView()
}
private func setupNavBar() {
let navigationBarAppearance = UINavigationBarAppearance()
navigationBarAppearance.configureWithOpaqueBackground()
navigationBarAppearance.shadowColor = .clear
navigationController?.navigationBar.standardAppearance = navigationBarAppearance
navigationController?.navigationBar.scrollEdgeAppearance = navigationBarAppearance
navigationController?.navigationBar.tintColor = Constant.ColorSetting.themeColor
navigationController?.navigationBar.prefersLargeTitles = false
navigationController?.setNeedsStatusBarAppearanceUpdate()
navigationController?.navigationBar.isTranslucent = false
navigationItem.scrollEdgeAppearance = navigationBarAppearance
navigationItem.standardAppearance = navigationBarAppearance
navigationItem.compactAppearance = navigationBarAppearance
navigationItem.rightBarButtonItem = UIBarButtonItem(image: UIImage(systemName: "bookmark.fill"), style: .plain, target: self, action: #selector(addButtonTapped))
navigationItem.rightBarButtonItem?.tintColor = Constant.ColorSetting.themeColor
navigationItem.title = Constant.MenuSetting.menuName2
self.extendedLayoutIncludesOpaqueBars = true
}
override func loadView() {
view = calcTypeView
}
private func setupView() {
view.backgroundColor = .systemBackground
}
#objc private func addButtonTapped() {
let bookmarkVC = BookmarkViewController()
navigationController?.pushViewController(bookmarkVC, animated: true)
}
}
My Screenshot
A scroll view's contentLayoutGuide defines the size of the scrollable area of the scroll view. The default size is 0,0.
In your code your contentView1 has no intrinsic size. It simply has a default size of 0,0. So your constraints are telling the scroll view to make its contentLayoutGuide to be 40,40 (based on the 20 and -20 constants) and leave the contentView1 size as 0,0.
If you setup contentView1 with specific width and height constraints then the scroll view's content size would be correct so that contentView1 would scroll within the scroll view.
A better example might be to add a UIStackView with a bunch of labels. Since the stack view will have an intrinsic size based on its content and setup, the contentLayoutGuide of the scroll view will fit around the stack view's intrinsic size.

Why my 2D UIViews don't appear on screen?

I'm trying to make UIView that contains 12x7 UIViews with margins. I thought that the best way gonna be make 7 Vertical Stacks and then add all them on one big Horizontal stack. And I coded it, but problem is that this Horizontal Stacks doesn't appear on the screen at all (I've tried Xcode feature to see layers there is nothing).
This is my code:
import UIKit
class CalendarView: UIView {
override init(frame: CGRect) {
super.init(frame: frame)
setupView()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setupView()
}
private func setupView() {
// array to add in future in columnsStackView
var columnStacks: [UIStackView] = []
for columns in 1...12 {
// array to add in future in columnStackView
var columnViews: [UIView] = []
for cell in 1...7 {
let cellView = UIView(frame: CGRect(x: 0, y: 0, width: 24, height: 24))
cellView.backgroundColor = .orange
columnViews.append(cellView)
}
// create columnStackView and add all 7 views
let columnStackView = UIStackView(arrangedSubviews: columnViews)
columnStackView.axis = .vertical
columnStackView.distribution = .fillEqually
columnStackView.alignment = .fill
columnStackView.spacing = 4
columnStacks.append(columnStackView)
}
// create columnsStackView and add those 12 stacks
let columnsStackView = UIStackView(arrangedSubviews: columnStacks)
columnsStackView.axis = .horizontal
columnsStackView.distribution = .fillEqually
columnsStackView.alignment = .fill
columnsStackView.spacing = 4
columnsStackView.translatesAutoresizingMaskIntoConstraints = false
self.addSubview(columnsStackView)
}
}
Can you please help me with that!!!
Couple things...
A UIStackView uses auto-layout when arranging its subviews, so this line:
let cellView = UIView(frame: CGRect(x: 0, y: 0, width: 24, height: 24))
will create a UIView, but the width and height will be ignored.
You need to set those with constraints:
for cell in 1...7 {
let cellView = UIView()
cellView.backgroundColor = .orange
// we want each "cellView" to be 24x24 points
cellView.widthAnchor.constraint(equalToConstant: 24.0).isActive = true
cellView.heightAnchor.constraint(equalTo: cellView.widthAnchor).isActive = true
columnViews.append(cellView)
}
Now, because we've explicitly set the width and height of the "cellViews" we can set the stack view .distribution = .fill (instead of .fillEqually).
Next, we have to constrain the "outer" stack view (columnsStackView) to the view itself:
// constrain the "outer" stack view to self
NSLayoutConstraint.activate([
columnsStackView.topAnchor.constraint(equalTo: topAnchor),
columnsStackView.leadingAnchor.constraint(equalTo: leadingAnchor),
columnsStackView.trailingAnchor.constraint(equalTo: trailingAnchor),
columnsStackView.bottomAnchor.constraint(equalTo: bottomAnchor),
])
otherwise, the view will have 0x0 dimensions.
Here is a modified version of your class:
class CalendarView: UIView {
override init(frame: CGRect) {
super.init(frame: frame)
setupView()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setupView()
}
private func setupView() {
// array to add in future in columnsStackView
var columnStacks: [UIStackView] = []
for columns in 1...12 {
// array to add in future in columnStackView
var columnViews: [UIView] = []
for cell in 1...7 {
let cellView = UIView()
cellView.backgroundColor = .orange
// we want each "cellView" to be 24x24 points
cellView.widthAnchor.constraint(equalToConstant: 24.0).isActive = true
cellView.heightAnchor.constraint(equalTo: cellView.widthAnchor).isActive = true
columnViews.append(cellView)
}
// create columnStackView and add all 7 views
let columnStackView = UIStackView(arrangedSubviews: columnViews)
columnStackView.axis = .vertical
columnStackView.distribution = .fill
columnStackView.alignment = .fill
columnStackView.spacing = 4
columnStacks.append(columnStackView)
}
// create columnsStackView and add those 12 stacks
let columnsStackView = UIStackView(arrangedSubviews: columnStacks)
columnsStackView.axis = .horizontal
columnsStackView.distribution = .fill
columnsStackView.alignment = .fill
columnsStackView.spacing = 4
columnsStackView.translatesAutoresizingMaskIntoConstraints = false
self.addSubview(columnsStackView)
// constrain the "outer" stack view to self
NSLayoutConstraint.activate([
columnsStackView.topAnchor.constraint(equalTo: topAnchor),
columnsStackView.leadingAnchor.constraint(equalTo: leadingAnchor),
columnsStackView.trailingAnchor.constraint(equalTo: trailingAnchor),
columnsStackView.bottomAnchor.constraint(equalTo: bottomAnchor),
])
}
}
and a simple test controller to show how it can be used:
class CalendarTestViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let cv = CalendarView()
cv.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(cv)
// the CalendarView will size itself, so we only need to
// provide x and y position constraints
NSLayoutConstraint.activate([
cv.centerXAnchor.constraint(equalTo: view.centerXAnchor),
cv.centerYAnchor.constraint(equalTo: view.centerYAnchor),
])
// let's give it a background color so we can see its frame
cv.backgroundColor = .systemYellow
}
}
the result:

How to dynamically resize text view inside a stack view

I'm trying to display a dynamically sized UITextView inside a stack view, but the text view is not adjusting to the size of the content.
First I have the arranged subview:
class InfoView: UIView {
private var title: String!
private var detail: String!
private var titleLabel: UILabel!
private var detailTextView: UITextView!
init(infoModel: InfoModel) {
self.title = infoModel.title
self.detail = infoModel.detail
super.init(frame: .zero)
configure()
setConstraint()
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
private func configure() {
titleLabel = UILabel()
titleLabel.text = title
titleLabel.font = .rounded(ofSize: titleLabel.font.pointSize, weight: .bold)
titleLabel.textColor = .lightGray
titleLabel.sizeToFit()
titleLabel.translatesAutoresizingMaskIntoConstraints = false
self.addSubview(titleLabel)
detailTextView = UITextView()
detailTextView.sizeToFit()
detailTextView.text = detail
detailTextView.font = UIFont.systemFont(ofSize: 19)
detailTextView.isEditable = false
detailTextView.textColor = .lightGray
detailTextView.isUserInteractionEnabled = false
detailTextView.isScrollEnabled = false
detailTextView.translatesAutoresizingMaskIntoConstraints = false
self.addSubview(detailTextView)
}
private func setConstraint() {
NSLayoutConstraint.activate([
titleLabel.topAnchor.constraint(equalTo: self.topAnchor),
titleLabel.leadingAnchor.constraint(equalTo: self.leadingAnchor, constant: 5),
titleLabel.heightAnchor.constraint(equalToConstant: 40),
detailTextView.topAnchor.constraint(equalTo: titleLabel.bottomAnchor),
detailTextView.leadingAnchor.constraint(equalTo: self.leadingAnchor),
detailTextView.trailingAnchor.constraint(equalTo: self.trailingAnchor),
detailTextView.bottomAnchor.constraint(equalTo: self.bottomAnchor)
])
}
}
Then I implement the stack view in a view controller:
class MyViewController: UIViewController {
var infoModelArr: [InfoModel]!
var stackView: UIStackView!
var scrollView: UIScrollView!
init(infoModelArr: [InfoModel]) {
self.infoModelArr = infoModelArr
super.init(nibName: nil, bundle: nil)
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
var infoViewArr = [InfoView]()
for infoModel in infoModelArr {
let infoView = InfoView(infoModel: infoModel)
infoViewArr.append(infoView)
}
stackView = UIStackView(arrangedSubviews: infoViewArr)
stackView.axis = .vertical
stackView.spacing = 10
stackView.distribution = .fillProportionally
stackView.translatesAutoresizingMaskIntoConstraints = false
scrollView.addSubview(stackView)
NSLayoutConstraint.activate([
stackView.topAnchor.constraint(equalTo: scrollView.topAnchor),
stackView.leadingAnchor.constraint(equalTo: view.layoutMarginsGuide.leadingAnchor),
stackView.trailingAnchor.constraint(equalTo: view.layoutMarginsGuide.trailingAnchor),
])
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
scrollView.contentSize = stackView.bounds.size
}
}
Finally, I call the view controller as following:
let myVC = MyViewController(infoModelArr: [InfoModel(title: "title", detail: "detail"), InfoModel(title: "title", detail: "detail")])
self.present(myVC, animated: true, completion: nil)
Notably, if I were to instantiate the stack view with a single arranged subview, the height of the stack view seems to be dynamically adjusted, but as soon as 2 or more subviews are introduced, the height doesn't reflect the content.
When I attempted to set the intrinsic size of the InfoView,
override func layoutSubviews() {
super.layoutSubviews()
height = titleLabel.bounds.height + detailTextView.bounds.height
}
var height: CGFloat! = 200 {
didSet {
self.invalidateIntrinsicContentSize()
}
}
override var intrinsicContentSize: CGSize {
let originalSize = super.intrinsicContentSize
return CGSize(width: originalSize.width, height: height)
}
detailTextView.bounds.height returns 0.
The fillProportionally distribution tries to scale the heights of the arranged subviews according to their intrinsic content size, as a proportion of of the stack view's height. e.g. if the stack view has a height of 120, and arranged subview A has an intrinsic height of 10, and arranged subview B has an intrinsic height of 20, then A and B will have a height of 40 and 80 respectively in the stack view.
Your stack view doesn't have a defined height, so fillProportionally doesn't make much sense here.
Instead, a distribution of fill should do the job:
stackView.distribution = .fill
(as an experiment, you can try adding a height constraint to the stack view, and you'll see how fillProportionally works)

Is it possible to load UIStackView arrangedSubviews after init

I have a View which contains a UIStackView, this UIStackView arrangedSubviews is an array of UIButtons. What happens is that when I'm on ViewDidLoad of my ViewController, I set an array of UIButtons like this:
let buttons = [button1, button2, button3, button4]
The number of buttons can vary from 1 to 4.
On the View file I have a variable with didSet, on that didSet I set an array in the view to have the contents of the buttons array.
The problem is that the didSet happens after the View's init(), so when I setup the UIStackView, the array is an empty array.
Is there a way to make the view to set the UIStackView again after the didSet, so I will have the array I need?
This is my View with the didSet and the array:
class ProductDetailView: UIView {
var productViewModel: ProductDetailViewModel? {
didSet {
self.quantityButtons = self.productViewModel?.quantityOptions ?? [] <--- This is where I set the buttons array.
}
}
//MARK: - Properties
var quantityButtons: [UIButton] = [] //TODO: This should be a custom button.
}
This is my UIStackView:
private lazy var quantitiesStack: UIStackView = {
let stack = UIStackView(arrangedSubviews: self.quantityButtons)
stack.translatesAutoresizingMaskIntoConstraints = false
stack.axis = .horizontal
stack.distribution = .fillEqually
stack.spacing = 2.0
return stack
}()
If it is not possible, how should I approach this issue? how can I have the populated array when I need it?
EDIT: I also tried this approach:
var quantityButtons: [UIButton] {
return productViewModel?.quantityOptions ?? []
}
still got an empty array.
I'm still kinda confused by what exactly you're doing, but I think I know what you want to do. You can copy paste the code into a new Xcode project and after a few second you'll see the buttons appear.
class ProductDetailView: UIView {
// The StackView for the buttons should be in this view.
private lazy var quantitiesStack: UIStackView = {
let stack = UIStackView(arrangedSubviews: self.quantityButtons)
stack.translatesAutoresizingMaskIntoConstraints = false
stack.axis = .horizontal
stack.distribution = .fillEqually
stack.spacing = 2.0
return stack
}()
//MARK: - Properties
var quantityButtons: [UIButton] = [] {
didSet {
guard !quantityButtons.isEmpty else { return }
// Might need to modify this if you update the buttons more than once.
guard quantitiesStack.arrangedSubviews.isEmpty else { return }
for button in quantityButtons {
// Adding these subviews will cause the stackview to be redraw with these buttons.
quantitiesStack.addArrangedSubview(button)
}
}
}
override init(frame: CGRect) {
super.init(frame: frame)
commonInit()
}
required init?(coder: NSCoder) {
super.init(coder: coder)
commonInit()
}
private func commonInit() {
// layout - this view is basically just a stackview.
addSubview(quantitiesStack)
quantitiesStack.translatesAutoresizingMaskIntoConstraints = false
quantitiesStack.topAnchor.constraint(equalTo: self.topAnchor).isActive = true
quantitiesStack.leadingAnchor.constraint(equalTo: self.leadingAnchor).isActive = true
quantitiesStack.trailingAnchor.constraint(equalTo: self.trailingAnchor).isActive = true
quantitiesStack.bottomAnchor.constraint(equalTo: self.bottomAnchor).isActive = true
}
}
class ViewController: UIViewController {
let productDetailView = ProductDetailView()
override func viewDidLoad() {
super.viewDidLoad()
view.addSubview(productDetailView)
productDetailView.backgroundColor = .lightGray
productDetailView.translatesAutoresizingMaskIntoConstraints = false
productDetailView.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor).isActive = true
productDetailView.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 16).isActive = true
productDetailView.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -16).isActive = true
// Simulate delay loading data.
DispatchQueue.main.asyncAfter(deadline: .now() + .seconds(3), execute: {
var buttons: [UIButton] = []
for i in 0..<4 {
let button = UIButton(type: .custom)
button.setTitle("Button \(i)", for: .normal)
button.titleLabel?.textColor = .black
buttons.append(button)
}
// This will trigger the buttons to be added to the stackView and then they will appear in the UI.
self.productDetailView.quantityButtons = buttons
})
}
}
Screenshot:

Load view from XIB as a subview of a scrollview

I'm still a SO and Swift newbie, so please, be patient and feel free to skip this question :-)
In the body of a XIB's awakeFromNib, I want to load some views as subviews of a UIScrollView (basically, the XIB contains a scrollview, a label and a button).
The scrollview perfectly works if in a loop I load views I create on the fly, eg.
let customView = UIView(frame: CGRect(x: 0, y: 0, width: 300, height: 150))
customView.frame = CGRect(x: i*300 , y: 0, width: 300, height: 150)
customView.translatesAutoresizingMaskIntoConstraints = false
scrollView.addSubview(customView)
But I have a different goal.
In another XIB I have an image view and a stackview with some labels. This XIB is connected in the storyboard to a class SingleEvent that extends UIView.
I want to do the following:
use the XIB as a sort of "blueprint" and load the same view multiple times in my scrollview;
pass to any instance some data;
Is this possible?
I tried to load the content of the XIB this way:
let customView = Bundle.main.loadNibNamed("SingleEvent", owner: self, options: nil)?.first as? SingleEvent
and this way:
let customView = SingleEvent()
The first one makes the app crash, while the second causes no issue, but I can't see any effect (it doesn't load anything).
The content of my latest SingleEvent is the following:
import UIKit
class SingleEvent: UIView {
#IBOutlet weak var label:UILabel!
#IBOutlet weak var imageView:UIImageView!
override init(frame: CGRect) {
super.init(frame: frame)
loadViewFromNib()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
loadViewFromNib()
}
func loadViewFromNib() -> UIView {
let myView = Bundle.main.loadNibNamed("SingleEvent", owner: self, options: nil)?.first as! UIView
return myView
}
}
Thanks in advance, any help is appreciated :-)
There are a number of approaches to loading custom views (classes) from xibs. You may find this method a bit easier.
First, create your xib like this:
Note that the Class of File's Owner is the default (NSObject).
Instead, assign your custom class to the "root" view in your xib:
Now, our entire custom view class looks like this:
class SingleEvent: UIView {
#IBOutlet var topLabel: UILabel!
#IBOutlet var middleLabel: UILabel!
#IBOutlet var bottomLabel: UILabel!
#IBOutlet var imageView: UIImageView!
}
And, instead of putting loadNibNamed(...) inside our custom class, we create a UIView extension:
extension UIView {
class func fromNib<T: UIView>() -> T {
return Bundle.main.loadNibNamed(String(describing: T.self), owner: nil, options: nil)![0] as! T
}
}
To load and use our custom class, we can do this:
class FromXIBViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// create an instance of SingleEvent from its xib/nib
let v = UIView.fromNib() as SingleEvent
// we're going to use auto-layout & constraints
v.translatesAutoresizingMaskIntoConstraints = false
// set the text of the labels
v.topLabel?.text = "Top Label"
v.middleLabel?.text = "Middle Label"
v.bottomLabel?.text = "Bottom Label"
// set the image
v.imageView.image = UIImage(named: "myImage")
// add the SingleEvent view
view.addSubview(v)
// constrain it 200 x 200, centered X & Y
NSLayoutConstraint.activate([
v.widthAnchor.constraint(equalToConstant: 200.0),
v.heightAnchor.constraint(equalToConstant: 200.0),
v.centerXAnchor.constraint(equalTo: view.centerXAnchor),
v.centerYAnchor.constraint(equalTo: view.centerYAnchor),
])
}
}
With a result of:
And... here is an example of loading 10 instances of SingleEvent view and adding them to a vertical scroll view:
class FromXIBViewController: UIViewController {
var theScrollView: UIScrollView = {
let v = UIScrollView()
v.translatesAutoresizingMaskIntoConstraints = false
v.backgroundColor = .cyan
return v
}()
var theStackView: UIStackView = {
let v = UIStackView()
v.translatesAutoresizingMaskIntoConstraints = false
v.axis = .vertical
v.alignment = .fill
v.distribution = .fill
v.spacing = 20.0
return v
}()
override func viewDidLoad() {
super.viewDidLoad()
// add the scroll view to the view
view.addSubview(theScrollView)
// constrain it 40-pts on each side
NSLayoutConstraint.activate([
theScrollView.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor, constant: 40.0),
theScrollView.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor, constant: -40.0),
theScrollView.leadingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.leadingAnchor, constant: 40.0),
theScrollView.trailingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.trailingAnchor, constant: -40.0),
])
// add a stack view to the scroll view
theScrollView.addSubview(theStackView)
// constrain it 20-pts on each side
NSLayoutConstraint.activate([
theStackView.topAnchor.constraint(equalTo: theScrollView.topAnchor, constant: 20.0),
theStackView.bottomAnchor.constraint(equalTo: theScrollView.bottomAnchor, constant: -20.0),
theStackView.leadingAnchor.constraint(equalTo: theScrollView.leadingAnchor, constant: 20.0),
theStackView.trailingAnchor.constraint(equalTo: theScrollView.trailingAnchor, constant: -20.0),
// stackView width = scrollView width -40 (20-pts padding on left & right
theStackView.widthAnchor.constraint(equalTo: theScrollView.widthAnchor, constant: -40.0),
])
for i in 0..<10 {
// create an instance of SingleEvent from its xib/nib
let v = UIView.fromNib() as SingleEvent
// we're going to use auto-layout & constraints
v.translatesAutoresizingMaskIntoConstraints = false
// set the text of the labels
v.topLabel?.text = "Top Label: \(i)"
v.middleLabel?.text = "Middle Label: \(i)"
v.bottomLabel?.text = "Bottom Label: \(i)"
// set the image (assuming we have images named myImage0 thru myImage9
v.imageView.image = UIImage(named: "myImage\(i)")
theStackView.addArrangedSubview(v)
}
}
}
Result:
Ok, I see. The problem probably in fact that loadViewFromNib function return UIView from xib, but you doesn't use it any way.
Let's try this way:
1) Make your loadViewFromNib function static
// Return our SingleEvent instance here
static func loadViewFromNib() -> SingleEvent {
let myView = Bundle.main.loadNibNamed("SingleEvent", owner: self, options: nil)?.first as! SingleEvent
return myView
}
2) Remove all inits in SingleEvent class
3) Init it in needed place like this:
let customView = SingleView.loadViewFromNib()
To pass data inside view you can create new function in SingleView class:
func configureView(with dataModel:DataModel) {
//Set data to IBOutlets here
}
And use it from outside like this:
let customView = SingleView.loadViewFromNib()
let dataModel = DataModel()
customView.configureView(with: dataModel)

Resources