I'm new to IOS development.
The followings are what I want to implement
- Have a two container in the main view
- In the first container, add a UICollectionView
- In the second container, add a UITableView
This is the code that I've done so far.
Main View:
class MainViewController:UIViewController {
let itemView:UIView = {
let itemContainerView = UIView()
itemContainerView.backgroundColor = UIColor.lightGray
let collectionView = CollectionViewController()
itemContainerView.addSubview(collectionView.view)
itemContainerView.translatesAutoresizingMaskIntoConstraints = false
return itemContainerView
}()
let tableView:UIView = {
let tableContainerView = UIView()
tableContainerView.backgroundColor = UIColor.gray
tableContainerView.translatesAutoresizingMaskIntoConstraints = false
return tableContainerView
}()
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = UIColor.white
view.addSubview(itemView)
view.addSubview(tableView)
setupItemView()
setupTableView()
}
func setupItemView(){
itemView.topAnchor.constraint(equalTo: view.topAnchor).isActive = true
itemView.leftAnchor.constraint(equalTo: view.leftAnchor).isActive = true
itemView.widthAnchor.constraint(equalTo: view.widthAnchor, multiplier: 2/3).isActive = true
itemView.heightAnchor.constraint(equalTo: view.heightAnchor).isActive = true
}
func setupTableView() {
tableView.topAnchor.constraint(equalTo: view.topAnchor).isActive = true
tableView.leftAnchor.constraint(equalTo: itemView.rightAnchor).isActive = true
tableView.widthAnchor.constraint(equalTo: view.widthAnchor, multiplier: 1/3).isActive = true
tableView.heightAnchor.constraint(equalTo: view.heightAnchor).isActive = true
}
}
CollectionViewController:
class CollectionViewController:UIViewController, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
let cellId = "CellId"
var colView: UICollectionView!
override func viewDidLoad() {
super.viewDidLoad()
let layout = UICollectionViewFlowLayout()
layout.sectionInset = UIEdgeInsets(top: 20, left: 10, bottom: 10, right: 10)
layout.itemSize = CGSize(width: 111, height: 111)
colView = UICollectionView(frame: self.view.frame, collectionViewLayout: layout)
colView.delegate = self
colView.dataSource = self
colView.register(UICollectionViewCell.self, forCellWithReuseIdentifier: cellId)
colView.backgroundColor = UIColor.white
colView.translatesAutoresizingMaskIntoConstraints = false
self.view.addSubview(colView)
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 10
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellId, for: indexPath)
cell.backgroundColor = UIColor.brown
return cell
}
}
I could see my main screen has two container but couldn't see 10 collection cells.
Could anyone advise me to the right direction? Thanks in advance.
UPDATED
When I set MainViewController as the initial view, it's properly working.
However, in my project, MainViewController is not the initial view.
The flow is;
1. User login
2. Dashboard with a button will appear
3. Clicking button will navigate the user to MainViewController.
Here's my Dashboard class
class DashboardController: UIViewController{
let orderBtn:UIButton = {
let button = UIButton(type: .system)
button.backgroundColor = UIColor.init(red: 173/255, green: 184/255, blue: 255/255, alpha: 1)
button.layer.cornerRadius = 5
button.setTitle("Select Item" , for: .normal)
button.setTitleColor(UIColor.white, for: .normal)
button.titleLabel?.font = UIFont.boldSystemFont(ofSize: 16)
button.translatesAutoresizingMaskIntoConstraints = false
button.addTarget(self, action: #selector(handleOrderNavigation), for: .touchUpInside)
return button
}()
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = UIColor.white
view.addSubview(orderBtn)
setupOrderBtn()
}
func handleOrderNavigation() {
let mainViewController= MainViewController()
let mainViewNavController= UINavigationController(rootViewController: mainViewController)
self.present(mainViewNavController, animated: false, completion: nil)
}
}
Your code is proper working. here is the output I got from your collectionView code work.
Suggestion
Check view hierarchy of your UI and see is there is any collectionView present in your UI.
Ensure your methods are properly calling. Check it by adding break point.
Edit
You declaration of MainViewController is wrong in button action.
Instead of present MainViewController use push to MainViewController
Be ensure your button action method is properly calling on button click.
Try to call reloadData at some point after the view is loaded.
Related
I am using a UICollectionViewController to display a collection of UICollectionViewCell that a user can swipe between, on ios 13, swift 5, and UIKit. I ultimatelly want to re-draw the cell if the user has changed the orientation. In my controller, I have noticed that this piece of code gets executed on orientation change:
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cellId", for: indexPath) as! MyCell
return cell
}
In MyCell, I am using this code to monitor then a layout is re-initialized:
override init(frame: CGRect) {
super.init(frame: frame)
setLayout()
print("### orientation:: \(UIDevice.current.orientation.isLandscape) ")
}
Result: This method is called 2 times. When the app starts, and when I change from portrait to landscape. Any subsequent changes, do not call it. I suspect that this is fine, as maybe both versions are cached ( a landscape and a portrait ). If I add code to the setLayout() method based on the UIDevice.current.orientation.isLandscape flag, nothing changes while it executes. Note: The actual result of UIDevice.current.orientation.isLandscape is correct.
Here is an example of what is in my setLayout() method:
let topImageViewContainer = UIView();
topImageViewContainer.translatesAutoresizingMaskIntoConstraints = false
topImageViewContainer.backgroundColor = .yellow
addSubview(topImageViewContainer)
NSLayoutConstraint.activate([
topImageViewContainer.topAnchor.constraint(equalTo: topAnchor),
topImageViewContainer.leftAnchor.constraint(equalTo: leftAnchor),
topImageViewContainer.rightAnchor.constraint(equalTo: rightAnchor),
topImageViewContainer.heightAnchor.constraint(equalTo: heightAnchor, multiplier: 0.5)
])
if (UIDevice.current.orientation.isLandscape) {
let imageView = UIImageView(image: UIImage(named: "photo_a"))
imageView.translatesAutoresizingMaskIntoConstraints = false
imageView.contentMode = .scaleAspectFit
topImageViewContainer.addSubview(imageView)
} else {
let imageView = UIImageView(image: UIImage(named: "photo_b"))
imageView.translatesAutoresizingMaskIntoConstraints = false
imageView.contentMode = .scaleAspectFit
topImageViewContainer.addSubview(imageView)
}
In the example above, the code with "photo_a" is executing, but the ui is still showing photo_b. I suspect I am doing something wrong, and I need to somehow migrate towards an "Adaptive layout" as mentioned here: Different layouts in portrait and landscape mode . However, I am not sure how I could hook in some "viewWillTransition*" functions into a UICollectionViewCell that has a UIView.
How can I adjust my MyCell class, that implements UICollectionViewCell, to allow the cell to be updated when the user changes from landscape to protrait in a Swift intended way?
Hi try to check if is landscape or portrait in cellForItem, my example:
set colloectionView, flowLayaout and cell id:
class ViewController: UIViewController {
private var collectionView: UICollectionView?
let layout = UICollectionViewFlowLayout()
let cellId = "cellId"
now in viewDidLoad set collection view and layout parameters and the collection constraints:
layout.scrollDirection = .horizontal
collectionView = UICollectionView(frame: .zero, collectionViewLayout: layout)
collectionView?.delegate = self
collectionView?.dataSource = self
collectionView?.backgroundColor = .clear
collectionView?.register(BottomCellTableViewCell.self, forCellWithReuseIdentifier: cellId)
collectionView?.contentInset = UIEdgeInsets(top: 0, left: 10, bottom: 0, right: 10)
collectionView?.showsHorizontalScrollIndicator = false
collectionView?.translatesAutoresizingMaskIntoConstraints = false
guard let collection = collectionView else { return }
view.addSubview(collection)
layout.itemSize = CGSize(width: view.bounds.size.width / 2, height: 200)
collection.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor, constant: -20).isActive = true
collection.leadingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.leadingAnchor, constant: 0).isActive = true
collection.trailingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.trailingAnchor, constant: 0).isActive = true
collection.heightAnchor.constraint(equalToConstant: 200).isActive = true
after that conform to delegate and datasource in a separate extension (more clean code) and set in it numberOfItems and cellForRow:
extension ViewController: UICollectionViewDelegate, UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 10
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellId, for: indexPath) as! BottomCellTableViewCell
// check here device orientation
if UIDevice.current.orientation.isLandscape {
let image = UIImage(named: "meB")
cell.imageV.image = image
} else {
let image = UIImage(named: "me")
cell.imageV.image = image
}
// reload the view and the collection
DispatchQueue.main.async {
self.collectionView?.reloadData()
}
return cell
}
}
In collectionViewCell adding a subview directly to the cell, and pinning the image view to the cell, is wrong. You add it to a contentView and pin to it relative constraints:
class BottomCellTableViewCell: UICollectionViewCell {
let imageV: UIImageView = {
let iv = UIImageView()
iv.image = UIImage(named: "me")
iv.contentMode = .scaleAspectFill
iv.clipsToBounds = true
iv.translatesAutoresizingMaskIntoConstraints = false
return iv
}()
override init(frame: CGRect) {
super.init(frame: frame)
contentView.backgroundColor = .red
contentView.addSubview(imageV)
imageV.topAnchor.constraint(equalTo: contentView.topAnchor).isActive = true
imageV.leadingAnchor.constraint(equalTo: contentView.leadingAnchor).isActive = true
imageV.trailingAnchor.constraint(equalTo: contentView.trailingAnchor).isActive = true
imageV.bottomAnchor.constraint(equalTo: contentView.bottomAnchor).isActive = true
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
This is the result:
I'm creating a simple app using Swift 5, Xcode 11, and a ui table view controller. Inside the ui table view, I want 2 buttons: One button on the left of my table view, the other on the right. I have tried many other related/similar question's answers, but all of them failed(probably because 1. Too Old, 2. Answer written in OBJ-C).
Here's my Table View Controller:
import UIKit
#objcMembers class CustomViewController: UITableViewController {
var tag = 0
override func viewDidLoad() {
super.viewDidLoad()
}
override func viewDidAppear(_ animated: Bool) {
}
override func numberOfSections(in tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 1
}
// 3
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
tag = tag + 1
let cell = tableView.dequeueReusableCell(withIdentifier: "themeCell", for: indexPath) as! ThemeCell
var cellButton: UIButton!
cellButton = UIButton(frame: CGRect(x: 5, y: 5, width: 50, height: 30))
cell.addSubview(cellButton)
cell.img.image = UIImage(named: SingletonViewController.themes[indexPath.row])
cell.accessoryView = cellButton
cellButton.backgroundColor = UIColor.red
cellButton.tag = tag
return cell
}
}
Here's what I'm currently getting:
add below code for apply constraint worked
let cellButton = UIButton(frame: CGRect.zero)
cellButton.translatesAutoresizingMaskIntoConstraints = false
cell.addSubview(cellButton)
cell.accessoryView = cellButton
cellButton.backgroundColor = UIColor.red
cellButton.leadingAnchor.constraint(equalTo: cell.leadingAnchor, constant: 5).isActive = true
cellButton.topAnchor.constraint(equalTo: cell.topAnchor, constant: 5).isActive = true
cellButton.widthAnchor.constraint(equalToConstant: 50).isActive = true
cellButton.heightAnchor.constraint(equalToConstant: 30).isActive = true
You can achieve right and left align button from constraints.
Below is my code to align view right or left.
override func viewDidLoad() {
let leftButton = UIButton(type: .custom)
leftButton.backgroundColor = UIColor.red
self.view.addSubview(leftButton)
leftButton.translatesAutoresizingMaskIntoConstraints = false
let horizontalConstraint = leftButton.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 20)
let verticalConstraint = leftButton.centerYAnchor.constraint(equalTo: view.centerYAnchor)
let widthConstraint = leftButton.widthAnchor.constraint(equalToConstant: 100)
let heightConstraint = leftButton.heightAnchor.constraint(equalToConstant: 100)
NSLayoutConstraint.activate([horizontalConstraint, verticalConstraint, widthConstraint, heightConstraint])
let rightButton = UIButton(type: .custom)
rightButton.backgroundColor = UIColor.red
self.view.addSubview(rightButton)
rightButton.translatesAutoresizingMaskIntoConstraints = false
let horizontalConstraintRight = rightButton.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -20)
let verticalConstraintRight = rightButton.centerYAnchor.constraint(equalTo: view.centerYAnchor)
let widthConstraintRight = rightButton.widthAnchor.constraint(equalToConstant: 100)
let heightConstraintRight = rightButton.heightAnchor.constraint(equalToConstant: 100)
NSLayoutConstraint.activate([horizontalConstraintRight, verticalConstraintRight, widthConstraintRight, heightConstraintRight])
}
[![Left and Right Aligned View Constraints][1]][1]
[1]: https://i.stack.imgur.com/tMJ8N.jpg
As the cell is getting reuse, you have to put buttons in your xib file. You should not make a button every time and add it in a cell. Try this by adding a button in xib.
class ThemeCell: UITableViewCell {
//MARK:- Initialize View
private let button : UIButton = {
let button = UIButton()
button.setTitle("Hello", .normal)
button.backgroundColor = .red
button.translatesAutoresizingMaskIntoConstraints = false
return button
}()
//MARK:- View Life Cycle
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
setup()
}
override func awakeFromNib() {
super.awakeFromNib()
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
selectionStyle = .none
}
//MARK:- User Defined Function
private func setup() {
addSubView(button)
button.leadingAnchor.constraint(equalTo: leadingAnchor, constant: 20).isActive = true
button.topAnchor.constraint(equalTo: topAnchor, constant: 20).isActive = true
button.bottomAnchor.constraint(equalTo: bottomAnchor, constant: -20).isActive = true
}
}
You can use AutoLayout Constraints like this to setup the button. No need to call it in the cellForRow method.
I am building application where you have custom keyboard.
Inside it's class I have created collection view, here is code:
class KeyboardViewController: UIInputViewController, UICollectionViewDelegateFlowLayout, UICollectionViewDataSource, UICollectionViewDelegate {
let stickerImages = [
UIImage(named: "Image-1"),
UIImage(named: "Image-2"),
UIImage(named: "Image-3"),
UIImage(named: "Image-4"),
UIImage(named: "Image-5")
]
#IBOutlet var nextKeyboardButton: UIButton!
#IBOutlet var collectionView: UICollectionView!
override func updateViewConstraints() {
super.updateViewConstraints()
}
override func viewDidLoad() {
super.viewDidLoad()
let layout: UICollectionViewFlowLayout = UICollectionViewFlowLayout()
layout.scrollDirection = UICollectionView.ScrollDirection.vertical
layout.sectionInset = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
layout.itemSize = CGSize(width: 50, height: 50)
collectionView = UICollectionView(frame: self.view.frame, collectionViewLayout: layout)
collectionView.dataSource = self
collectionView.delegate = self
collectionView.register(StickersCell.self, forCellWithReuseIdentifier: StickersCell.reuseIdentifier)
collectionView.backgroundColor = UIColor.white
collectionView.showsHorizontalScrollIndicator = false
collectionView.backgroundColor = UIColor.red
collectionView.translatesAutoresizingMaskIntoConstraints = false
self.view.addSubview(collectionView)
self.nextKeyboardButton = UIButton(type: .system)
self.nextKeyboardButton.setTitle(NSLocalizedString("Next Keyboard", comment: "Title for 'Next Keyboard' button"), for: [])
self.nextKeyboardButton.sizeToFit()
self.nextKeyboardButton.translatesAutoresizingMaskIntoConstraints = false
self.nextKeyboardButton.backgroundColor = UIColor.white
self.nextKeyboardButton.addTarget(self, action: #selector(handleInputModeList(from:with:)), for: .allTouchEvents)
self.view.addSubview(self.nextKeyboardButton)
self.nextKeyboardButton.leftAnchor.constraint(equalTo: self.view.leftAnchor).isActive = true
self.nextKeyboardButton.bottomAnchor.constraint(equalTo: self.view.bottomAnchor).isActive = true
self.collectionView.leftAnchor.constraint(equalTo: self.view.leftAnchor).isActive = true
self.collectionView.rightAnchor.constraint(equalTo: self.view.rightAnchor).isActive = true
self.collectionView.topAnchor.constraint(equalTo: self.view.topAnchor).isActive = true
self.collectionView.bottomAnchor.constraint(equalTo: self.view.bottomAnchor).isActive = true
}
override func textWillChange(_ textInput: UITextInput?) {
// The app is about to change the document's contents. Perform any preparation here.
}
override func textDidChange(_ textInput: UITextInput?) {
// The app has just changed the document's contents, the document context has been updated.
var textColor: UIColor
let proxy = self.textDocumentProxy
if proxy.keyboardAppearance == UIKeyboardAppearance.dark {
textColor = UIColor.white
} else {
textColor = UIColor.black
}
self.nextKeyboardButton.setTitleColor(textColor, for: [])
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return stickerImages.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: StickersCell.reuseIdentifier, for: indexPath) as! StickersCell
cell.setImage(stickerImages[indexPath.item]!)
return cell
}}
And here is my Collection View cell class:
class StickersCell: UICollectionViewCell {
static let reuseIdentifier: String = "StickersCell"
lazy var imageView: UIImageView = {
let imageView = UIImageView(frame: .zero)
imageView.contentMode = .scaleAspectFit
imageView.translatesAutoresizingMaskIntoConstraints = false
return imageView
}()
override init(frame: CGRect) {
super.init(frame: frame)
contentView.clipsToBounds = true
contentView.addSubview(imageView)
imageView.leftAnchor.constraint(equalTo: contentView.leftAnchor).isActive = true
imageView.rightAnchor.constraint(equalTo: contentView.rightAnchor).isActive = true
imageView.topAnchor.constraint(equalTo: contentView.topAnchor).isActive = true
imageView.bottomAnchor.constraint(equalTo: contentView.bottomAnchor).isActive = true
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func setImage(_ image: UIImage) {
imageView.image = image
}}
This code works just fine when adding collection view to any UIView or UIViewController, but when trying to add it to keyboard it throws such errors:
As far as I understand I have placed constraints wrong, but I don't understand what exactly is wrong, especially when it's working fine in simple views or view controllers.
I have googled allot and couldn't find any solutions...
Also this SO questions didn't help as well:
First question
Second question
Third question
I have also tried moving code that creates collection view into viewDidAppear and viewWillAppear methods but same no luck.
Another strange thing:
If I add simple UIView with same constraints to keyboard - everything is working fine. Problem seems to be specifically with collection view.
So, what I have missed? Would be grateful for any help, since I'm battling with this issue for over a week already...
UPDATE:
After reading Apple dev forums, idea came up to my mind:
I have created UITableView same as UICollectionView before and strangely it works. So there's next question:
Are you able to use UICollectionView as custom keyboard at all?
After battling with this issue for 2 weeks finally found working workaround:
For some reason you can't use UIImageView or MSStickerView inside UICollectionViewCell same as in iMessage Extension, so instead I just added transparent UIButton with UIImage inside this button and it worked!
Still don't know why you can't use images or views and couldn't find any specific info about it, but my solutions works and I hope this will help someone in future.
I'm setting up a UICollectionView inside a ViewController. However, it won't respond to any user interaction, didSelectItemAt function is not getting called and I am unable to scroll it.
I have set the DataSource and Delegate properly inside the viewDidLoad(). Here is my code:
class WelcomeController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout {
let padding: CGFloat = 30
var sources = [Source]()
let sourceCellId = "sourceCellId"
func fetchSources() {
ApiSourceService.sharedInstance.fetchSources() { (root: Sources) in
self.sources = root.source
self.sourceCollectionView.reloadData()
}
}
let backgroundImage: UIImageView = {
let iv = UIImageView()
iv.image = UIImage(named: "background")
iv.contentMode = .scaleAspectFill
iv.translatesAutoresizingMaskIntoConstraints = false
iv.clipsToBounds = false
return iv
}()
let overlayView: UIView = {
let view = UIView()
view.translatesAutoresizingMaskIntoConstraints = false
view.backgroundColor = .white
return view
}()
let logo: UIImageView = {
let iv = UIImageView()
iv.image = UIImage(named: "mylogo")
iv.translatesAutoresizingMaskIntoConstraints = false
iv.clipsToBounds = false
return iv
}()
let defaultButton: UIButton = {
let ub = UIButton()
ub.translatesAutoresizingMaskIntoConstraints = false
ub.setTitle("Inloggen met E-mail", for: .normal)
ub.setImage(UIImage(named: "envelope"), for: .normal)
ub.imageEdgeInsets = UIEdgeInsetsMake(15, 0, 15, 0)
ub.imageView?.contentMode = .scaleAspectFit
ub.contentHorizontalAlignment = .left
ub.titleLabel?.font = UIFont.init(name: "Raleway-Regular", size: 16)
ub.backgroundColor = .cuOrange
return ub
}()
let continueWithoutButton: UIButton = {
let ub = UIButton()
ub.translatesAutoresizingMaskIntoConstraints = false
let attributedString: NSMutableAttributedString = NSMutableAttributedString(string: "Doorgaan zonder in te loggen")
let textRange = NSMakeRange(0, attributedString.length)
attributedString.setColor(color: .cuOrange, forText: "Doorgaan")
ub.setAttributedTitle(attributedString, for: .normal)
ub.contentHorizontalAlignment = .center
ub.titleLabel?.font = UIFont.init(name: "Raleway-Regular", size: 16)
ub.titleLabel?.textColor = .white
return ub
}()
let sourceCollectionView: UICollectionView = {
let layout = UICollectionViewFlowLayout()
let cv = UICollectionView(frame: .zero, collectionViewLayout: layout)
cv.translatesAutoresizingMaskIntoConstraints = false
cv.backgroundColor = .white
return cv
}()
let termsButton: UIButton = {
let ub = UIButton()
ub.translatesAutoresizingMaskIntoConstraints = false
let attributedString: NSMutableAttributedString = NSMutableAttributedString(string: "Met het maken van een account \nof bij inloggen, ga ik akkoord \nmet servicevoorwaarden.")
let textRange = NSMakeRange(0, attributedString.length)
attributedString.setColor(color: .cuOrange, forText: "servicevoorwaarden")
ub.setAttributedTitle(attributedString, for: .normal)
ub.contentHorizontalAlignment = .center
ub.contentVerticalAlignment = .bottom
ub.titleLabel?.lineBreakMode = .byWordWrapping
ub.titleLabel?.font = UIFont.init(name: "Raleway-Regular", size: 14)
ub.titleLabel?.textColor = .white
ub.titleLabel?.textAlignment = .center
return ub
}()
override func viewDidLoad() {
super.viewDidLoad()
fetchSources()
sourceCollectionView.dataSource = self
sourceCollectionView.delegate = self
sourceCollectionView.register(SourceCell.self, forCellWithReuseIdentifier: sourceCellId)
view.addSubview(backgroundImage)
view.addSubview(overlayView)
backgroundImage.addSubview(termsButton)
backgroundImage.addSubview(logo)
backgroundImage.addSubview(sourceCollectionView)
backgroundImage.widthAnchor.constraint(lessThanOrEqualToConstant: 375).isActive = true
backgroundImage.heightAnchor.constraint(lessThanOrEqualToConstant: 667).isActive = true
backgroundImage.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
backgroundImage.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true
logo.centerXAnchor.constraint(equalTo: backgroundImage.centerXAnchor).isActive = true
logo.topAnchor.constraint(equalTo: backgroundImage.topAnchor, constant: padding).isActive = true
logo.widthAnchor.constraint(equalToConstant: 107).isActive = true
logo.heightAnchor.constraint(equalToConstant: 100).isActive = true
sourceCollectionView.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
sourceCollectionView.widthAnchor.constraint(equalTo: view.widthAnchor, constant: -(padding*1.5)).isActive = true
sourceCollectionView.topAnchor.constraint(equalTo: logo.bottomAnchor, constant: padding).isActive = true
sourceCollectionView.bottomAnchor.constraint(equalTo: termsButton.topAnchor, constant: -(padding*2)).isActive = true
termsButton.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: -padding).isActive = true
termsButton.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
termsButton.widthAnchor.constraint(equalTo: view.widthAnchor, constant: -(padding*2)).isActive = true
termsButton.heightAnchor.constraint(equalToConstant: 40).isActive = true
sourceCollectionView.reloadData()
}
#objc func closeWelcomeController() {
let appDelegate = UIApplication.shared.delegate as! AppDelegate
appDelegate.switchViewControllers()
self.dismiss(animated: true, completion: {
})
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let width = self.sourceCollectionView.frame.width
let height = CGFloat(50)
return CGSize(width: width, height: height)
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return sources.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
print(sources[indexPath.item].feed_name)
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: sourceCellId, for: indexPath) as! SourceCell
cell.preservesSuperviewLayoutMargins = true
cell.source = sources[indexPath.item]
return cell
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
print("selecting")
}}
Anyone knows what I am doing wrong here?
I hope there isn't just a "dumb" error inside the code why it's not working, but it's been eating my brain for the past few hours.
It seems that it is inappropriate to add sourceCollectionView as a subview in backgroundImage which is UIImageView! Logically, image view doesn't represent a container view (such as UIView UIStackView, UIScrollView) i.e even if the code lets you do that, it still non-sensible; Furthermore, even if adding a subview to an image view is ok (which is not), image views by default are user interaction disabled (userInteractionEnabled is false by default for image views), that's why you are unable to even scroll the collection view, it is a part (subview) of a disabled user interaction component.
In your viewDidLoad(), you are implementing:
backgroundImage.addSubview(termsButton)
backgroundImage.addSubview(logo)
backgroundImage.addSubview(sourceCollectionView)
Don't do this, instead, add them to main view of the view controller:
view.addSubview(termsButton)
view.addSubview(logo)
view.addSubview(sourceCollectionView)
For the purpose of checking if its the reason of the issue, at least do it for the collection view (view.addSubview(sourceCollectionView)).
And for the purpose of organizing the hierarchy of the view (which on is on top of the other), you could use both: bringSubview(toFront:) or sendSubview(toBack:). For instance, after adding the collection view into the view, you might need to:
view.bringSubview(toFront: sourceCollectionView)
to make sure that the collection view is on top of all components.
I see you add sourceCollectionView to subview of backgroundImage. Your backgroundImage is UIImageView so UIImageView doesn't have user interaction except you need to enable it. The problem of your code is
backgroundImage.addSubview(sourceCollectionView)
For my suggestion you should create UIView or other views that can interact with user interaction. It will work fine.
So I am trying to use protocols and delegates to connect two functions so I can perform some operation on a variable a collectionView in this case in a different file.
import Foundation
import UIKit
protocol EventCollectionCellDelegate: NSObjectProtocol {
func setupCollectionView(for eventCollectionView: UICollectionView?)
}
class EventCollectionCell:UICollectionViewCell {
weak var delegate: EventCollectionCellDelegate?
var eventArray = [EventDetails](){
didSet{
self.eventCollectionView.reloadData()
}
}
var enentDetails:Friend?{
didSet{
var name = "N/A"
var total = 0
seperator.isHidden = true
if let value = enentDetails?.friendName{
name = value
}
if let value = enentDetails?.events{
total = value.count
self.eventArray = value
seperator.isHidden = false
}
if let value = enentDetails?.imageUrl{
profileImageView.loadImage(urlString: value)
}else{
profileImageView.image = #imageLiteral(resourceName: "Tokyo")
}
self.eventCollectionView.reloadData()
setLabel(name: name, totalEvents: total)
}
}
let container:UIView={
let view = UIView()
view.translatesAutoresizingMaskIntoConstraints = false
view.layer.cornerRadius = 16
view.layer.borderColor = UIColor.lightGray.cgColor
view.layer.borderWidth = 0.3
return view
}()
//profile image view for the user
var profileImageView:CustomImageView={
let iv = CustomImageView()
iv.layer.masksToBounds = true
iv.layer.borderColor = UIColor.lightGray.cgColor
iv.layer.borderWidth = 0.3
iv.translatesAutoresizingMaskIntoConstraints = false
return iv
}()
//will show the name of the user as well as the total number of events he is attending
let labelNameAndTotalEvents:UILabel={
let label = UILabel()
label.textColor = .black
label.translatesAutoresizingMaskIntoConstraints = false
label.numberOfLines = 0
return label
}()
let seperator:UIView={
let view = UIView()
view.backgroundColor = .lightGray
view.translatesAutoresizingMaskIntoConstraints = false
return view
}()
//collectionview that contains all of the events a specific user will be attensing
let flow = UICollectionViewFlowLayout()
lazy var eventCollectionView = UICollectionView(frame: .zero, collectionViewLayout: flow)
// var eventCollectionView:UICollectionView?
override init(frame: CGRect) {
super.init(frame: frame)
self.setUpCell()
self.setupCollectionView(for: eventCollectionView)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func setupCollectionView(for eventCollectionView: UICollectionView?){
delegate?.setupCollectionView(for: eventCollectionView)
}
}
This is the file that creates a collectionViewCell with a collectionView in it. I am trying to perform some operation on that collectionView using the delegate pattern. My problem is that the delegate function is never called in the accompanying viewController. I feel like I have done everything right but nothing happens in the accompanying vc. Anyone notice what could possibly be wrong.
I have shown the code for the VC below
class FriendsEventsView: UIViewController,UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout,EventCollectionCellDelegate {
var friends = [Friend]()
var followingUsers = [String]()
var height:CGFloat = 0
var notExpandedHeight : CGFloat = 50
var isExpanded = [Bool]()
//so this is the main collectonview that encompasses the entire view
lazy var mainCollectionView:UICollectionView={
// the flow layout which is needed when you create any collection view
let flow = UICollectionViewFlowLayout()
//setting the scroll direction
flow.scrollDirection = .vertical
//setting space between elements
let spacingbw:CGFloat = 5
flow.minimumLineSpacing = spacingbw
flow.minimumInteritemSpacing = 0
//actually creating collectionview
let cv = UICollectionView(frame: .zero, collectionViewLayout: flow)
//register a cell for that collectionview
cv.register(EventCollectionCell.self, forCellWithReuseIdentifier: "events")
cv.translatesAutoresizingMaskIntoConstraints = false
//changing background color
cv.backgroundColor = .white
//sets the delegate of the collectionView to self. By doing this all messages in regards to the collectionView will be sent to the collectionView or you.
//"Delegates send messages"
cv.delegate = self
//sets the datsource of the collectionView to you so you can control where the data gets pulled from
cv.dataSource = self
//sets positon of collectionview in regards to the regular view
cv.contentInset = UIEdgeInsetsMake(spacingbw, 0, spacingbw, 0)
return cv
}()
lazy var eventCollectionView:UICollectionView={
let flow = UICollectionViewFlowLayout()
flow.scrollDirection = .vertical
let spacingbw:CGFloat = 5
flow.minimumLineSpacing = 0
flow.minimumInteritemSpacing = 0
let cv = UICollectionView(frame: .zero, collectionViewLayout: flow)
//will register the eventdetailcell
cv.translatesAutoresizingMaskIntoConstraints = false
cv.backgroundColor = .white
cv.register(EventDetailsCell.self, forCellWithReuseIdentifier: "eventDetails")
cv.delegate = self
cv.dataSource = self
cv.contentInset = UIEdgeInsetsMake(spacingbw, 0, spacingbw, 0)
cv.showsVerticalScrollIndicator = false
cv.bounces = false
return cv
}()
func setupCollectionView(for eventCollectionView: UICollectionView?) {
print("Attempting to create collectonView")
eventCollectionView?.backgroundColor = .blue
}
//label that will be displayed if there are no events
let labelNotEvents:UILabel={
let label = UILabel()
label.textColor = .lightGray
label.translatesAutoresizingMaskIntoConstraints = false
label.numberOfLines = 0
label.font = UIFont.italicSystemFont(ofSize: 14)
label.text = "No events found"
label.isHidden = true
return label
}()
override func viewDidLoad() {
super.viewDidLoad()
//will set up all the views in the screen
self.setUpViews()
self.navigationItem.rightBarButtonItem = UIBarButtonItem(image: #imageLiteral(resourceName: "close_black").withRenderingMode(.alwaysOriginal), style: .done, target: self, action: #selector(self.goBack))
}
func setUpViews(){
//well set the navbar title to Friends Events
self.title = "Friends Events"
view.backgroundColor = .white
//adds the main collection view to the view and adds proper constraints for positioning
view.addSubview(mainCollectionView)
mainCollectionView.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor, constant: 0).isActive = true
mainCollectionView.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor, constant: 0).isActive = true
mainCollectionView.rightAnchor.constraint(equalTo: view.rightAnchor, constant: 0).isActive = true
mainCollectionView.leftAnchor.constraint(equalTo: view.leftAnchor, constant: 0).isActive = true
//adds the label to alert someone that there are no events to the collectionview and adds proper constrains for positioning
mainCollectionView.addSubview(labelNotEvents)
labelNotEvents.centerYAnchor.constraint(equalTo: mainCollectionView.centerYAnchor, constant: 0).isActive = true
labelNotEvents.centerXAnchor.constraint(equalTo: mainCollectionView.centerXAnchor, constant: 0).isActive = true
//will fetch events from server
self.fetchEventsFromServer()
}
// MARK: CollectionView Datasource for maincollection view
//woll let us know how many cells are being displayed
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
print(friends.count)
isExpanded = Array(repeating: false, count: friends.count)
return friends.count
}
//will control the size of the cell that is displayed in the containerview
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
height = 100
let event = friends[indexPath.item]
if let count = event.events?.count,count != 0{
height += (CGFloat(count*40)+10)
}
return CGSize(width: collectionView.frame.width, height: height)
}
//will do the job of effieicently creating cells for the eventcollectioncell
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "events", for: indexPath) as! EventCollectionCell
cell.delegate = self
cell.enentDetails = friends[indexPath.item]
cell.eventCollectionView = eventCollectionView
return cell
}
}
I have cut the code down to what I believe is needed to answer the question for simplicity. Any help is appreciated
You set delegate after setupCollectionView. In your case, you can't call setupCollectionView before you set delegate, because setupCollectionView called in init