Problem with background in table when emulating Iphone Max Pro 12 - swift

I'm trying to emulate my app in different Iphone models but I'm also having the same mistake when I use a Max Pro 12. Anytime I use a tableViewContoller it seems not to fill the background cells completely. Just check my pictures. In the rest of models, including Max Pro 11 it's working ok. I don`t have any constraints because the I can't add them when I use tableViewController. Any suggestion?
Here you have my code.
import UIKit
import FirebaseAuth
class MenuCustomCellController: UITableViewCell {
#IBOutlet weak var imEvento: UIImageView!
#IBOutlet weak var txtNombreEvento: UILabel!
#IBOutlet weak var txtFechaEvento: UILabel!
#IBOutlet weak var txtEstadoEvento: UILabel!
}
class MenuInicialTableController: UITableViewController {
#IBOutlet weak var celdaUsuarios: UITableViewCell!
#IBOutlet weak var celdaEventos: UITableViewCell!
#IBOutlet weak var celdaBuscarEventos: UITableViewCell!
#IBOutlet weak var celdaGraficos: UITableViewCell!
#IBOutlet weak var celdaCerrar: UITableViewCell!
#IBOutlet weak var celdaAyuda: UITableViewCell!
override func viewWillAppear(_ animated: Bool) {
let tap = UITapGestureRecognizer(target: self, action: #selector(MenuInicialTableController.tapFunction))
celdaCerrar.isUserInteractionEnabled = true
celdaCerrar.addGestureRecognizer(tap)
let background = UIView()
tableView.backgroundView = background
tableView.backgroundView?.aplicarFondoDegradado()
tableView.layer.borderWidth = 2
tableView.layer.borderColor = UIColor.white.cgColor
tableView.layer.cornerRadius = 10
celdaUsuarios.layer.borderWidth = 1
celdaUsuarios.layer.borderColor = UIColor.white.cgColor
celdaUsuarios.layer.cornerRadius = 10
celdaUsuarios.contentView.aplicarFondoMenuUsuarios()
celdaEventos.layer.borderWidth = 1
celdaEventos.layer.borderColor = UIColor.white.cgColor
celdaEventos.layer.cornerRadius = 10
celdaEventos.contentView.aplicarFondoMenuEventos()
celdaGraficos.layer.borderWidth = 1
celdaGraficos.layer.borderColor = UIColor.white.cgColor
celdaGraficos.layer.cornerRadius = 10
celdaGraficos.contentView.aplicarFondoMenuEventos()
celdaCerrar.layer.borderWidth = 1
celdaCerrar.layer.borderColor = UIColor.white.cgColor
celdaCerrar.layer.cornerRadius = 10
celdaCerrar.contentView.aplicarFondoMenuUsuarios()
}
override func viewDidLoad() {
super.viewDidLoad()
self.title = "MENÚ PRINCIPAL"
self.navigationItem.setHidesBackButton(true, animated: true)
}
override func numberOfSections(in tableView: UITableView) -> Int {
return 2
}
//Dos filas por sección
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 2
}
#objc
func tapFunction(sender:UITapGestureRecognizer) {
exit(0)
}
}
And here you have how I apply gradients:
func aplicarFondoMenuUsuarios() {
let colorInicio = UIColor(red: 0/255, green: 0/255, blue: 0/255, alpha: 1.0).cgColor
let colorFin = UIColor(red: 0/255, green: 190/255, blue: 219/255, alpha: 1.0).cgColor
if let gradientLayer = layer.sublayers?.first as? CAGradientLayer {
gradientLayer.colors = [colorInicio,colorFin]
}
else{
let gradientLayer = CAGradientLayer()
gradientLayer.colors = [colorInicio, colorFin]
gradientLayer.startPoint = CGPoint(x: 0, y: 0.50)
gradientLayer.endPoint = CGPoint(x: 0.50, y: 1.00)
gradientLayer.frame = self.bounds
self.layer.insertSublayer(gradientLayer, at:0)
}
func aplicarFondoMenuEventos() {
let colorInicio = UIColor(red: 0/255, green: 0/255, blue: 0/255, alpha: 1.0).cgColor
let colorFin = UIColor(red: 15/255, green: 0/255, blue: 219/255, alpha: 1.0).cgColor
if let gradientLayer = layer.sublayers?.first as? CAGradientLayer {
gradientLayer.colors = [colorInicio,colorFin]
}
else{
let gradientLayer = CAGradientLayer()
gradientLayer.colors = [colorInicio, colorFin]
gradientLayer.startPoint = CGPoint(x: 0, y: 0.50)
gradientLayer.endPoint = CGPoint(x: 0.50, y: 1.00)
gradientLayer.frame = self.bounds
self.layer.insertSublayer(gradientLayer, at:0)
}
}

Don't use viewWillAppear for layout-code. And not for TapGestures either. Move the three first lines (tap-related) into viewDidLoad, and put the rest into override func viewDidLayoutSubviews(){}.
There are a lot of other stuff you should do as well, like subclassing the cells and have them perform their gradients at the time of their own layout, and you should also remove let background = UIView() and instead just say tableView.backgroundView = UIView() in viewDidLoad (not in willAppear and not in viewDidLayoutSubviews).

Related

Problem addient gradients to a custom cell background swift

I've created a custom class to apply different gradients as you can see. But my problem is that I can't use it to add gradient to a custom cell
import UIKit
extension UIView {
// MARK: - Creamos funcion para poder aplicar degrado vertical 2 colores
func aplicarFondoDegradado() {
let colorArriba = UIColor(red: 255/255, green: 4/255, blue: 14/255, alpha: 1.0).cgColor
let colorAbajo = UIColor(red: 0/255, green: 0/255, blue: 0/255, alpha: 1.0).cgColor
let gradientLayer = CAGradientLayer()
gradientLayer.colors = [colorArriba, colorAbajo]
gradientLayer.locations = [0.0, 1.0]
gradientLayer.frame = self.bounds
self.layer.insertSublayer(gradientLayer, at:0)
}
func aplicarDegradadoCultural() {
let colorInicio = UIColor(red: 0/255, green: 56/255, blue: 255/255, alpha: 1.0).cgColor
let colorFin = UIColor(red: 125/255, green: 195/255, blue: 226/255, alpha: 1.0).cgColor
let gradientLayer = CAGradientLayer()
gradientLayer.colors = [colorInicio, colorFin]
gradientLayer.startPoint = CGPoint(x: 0.0, y: 0.5)
// Set end point.
gradientLayer.endPoint = CGPoint(x: 1.0, y: 0.5)
gradientLayer.frame = self.bounds
self.layer.insertSublayer(gradientLayer, at:0)
}
func aplicarDegradadoDeportes() {
let colorInicio = UIColor(red: 0/255, green: 56/255, blue: 255/255, alpha: 1.0).cgColor
let colorFin = UIColor(red: 125/255, green: 195/255, blue: 226/255, alpha: 1.0).cgColor
let gradientLayer = CAGradientLayer()
gradientLayer.colors = [colorInicio, colorFin]
gradientLayer.startPoint = CGPoint(x: 0.0, y: 0.5)
gradientLayer.endPoint = CGPoint(x: 1.0, y: 0.5)
gradientLayer.frame = self.bounds
self.layer.insertSublayer(gradientLayer, at:0)
}
}
And It works but my problem is that when I tried to apply to a dinamic cell the gradient it's not shown.
This is my code for the tableview controller which includes the custom cell controller:
import UIKit
class EventosCustomCellController: UITableViewCell {
#IBOutlet weak var imEvento: UIImageView!
#IBOutlet weak var txtNombreEvento: UILabel!
#IBOutlet weak var txtFechaEvento: UILabel!
#IBOutlet weak var txtEstadoEvento: UILabel!
}
class ListaEventosTableViewController: UITableViewController {
override func viewDidLoad() {
super.viewDidLoad()
self.title = "Eventos"
}
// MARK: - Table view data source
override func viewWillAppear(_ animated: Bool) {
}
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return eventos.contarEventos()
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "prototipoCeldaEvento", for: indexPath) as! EventosCustomCellController
let evento = eventos.buscarEventoPorID(id: indexPath.row)
cell.layer.borderWidth = 1
cell.layer.borderColor = UIColor.black.cgColor
cell.imageView?.layer.cornerRadius = 30
cell.txtNombreEvento?.text = evento?.nombre
cell.txtFechaEvento?.text = evento?.fecha
cell.txtEstadoEvento?.text = evento?.tipo
//THE PROBLEM IS HERE THE GRADIENT IS NOT SHOWN
//THE PROBLEM IS HERE THE GRADIENT IS NOT SHOWN
if evento?.tipo == "deportivo"{
cell.aplicarDegradadoCultural()}
else if evento?.tipo == "cultural"{
cell.aplicarFondoDegradado() }
else{
cell.aplicarDegradadoDeportes()}
cell.layer.masksToBounds = true
cell.layer.cornerRadius = 10
cell.imEvento.loadFrom(URLAddress: (evento?.imagenes![0])!)
cell.imEvento.layer.cornerRadius = 25
cell.imEvento.clipsToBounds = true
cell.imEvento.layer.borderWidth = 3
cell.imEvento.layer.borderColor = UIColor.white.cgColor
return cell
}
// Override to support conditional editing of the table view.
override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
// Return false if you do not want the specified item to be editable.
return true
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
let celdaPulsada = tableView.indexPathForSelectedRow?.row
eventos.devolverCeldaPulsada (id: celdaPulsada!)
}}
You're doing a couple things wrong -- and, you'll find it much easier to use a custom "GradientView"
Cells are reused... with your extension UIView approach, you are inserting another gradient layer every time the cell is used.
Also, you're not guaranteed to have the correct frame at that point.
Here is a very simple, basic custom "GradientView":
class GradientView: UIView {
var gradientLayer: CAGradientLayer!
override class var layerClass: AnyClass {
return CAGradientLayer.self
}
override init(frame: CGRect) {
super.init(frame: frame)
commonInit()
}
required init?(coder: NSCoder) {
super.init(coder: coder)
commonInit()
}
func commonInit() -> Void {
gradientLayer = self.layer as? CAGradientLayer
}
}
Add a UIView to your cell's Content View in Storyboard, behind all of the labels, and constrain it to all 4 sides.
Then, assign its Custom Class to GradientView, and connect it to your cell class just like the labels:
#IBOutlet weak var gradientView: GradientView!
Then, delete your extension UIView and move those gradient funcs to your cell, so it looks like this:
class EventosCustomCellController: UITableViewCell {
#IBOutlet weak var imEvento: UILabel!
#IBOutlet weak var txtNombreEvento: UILabel!
#IBOutlet weak var txtFechaEvento: UILabel!
#IBOutlet weak var txtEstadoEvento: UILabel!
#IBOutlet weak var gradientView: GradientView!
func aplicarFondoDegradado() {
let colorArriba = UIColor(red: 255/255, green: 4/255, blue: 14/255, alpha: 1.0).cgColor
let colorAbajo = UIColor(red: 0/255, green: 0/255, blue: 0/255, alpha: 1.0).cgColor
gradientView.gradientLayer.colors = [colorArriba, colorAbajo]
gradientView.gradientLayer.locations = [0.0, 1.0]
// start/end points
gradientView.gradientLayer.startPoint = CGPoint(x: 0.5, y: 0.0)
gradientView.gradientLayer.endPoint = CGPoint(x: 0.5, y: 1.0)
}
func aplicarDegradadoCultural() {
let colorInicio = UIColor(red: 0/255, green: 56/255, blue: 255/255, alpha: 1.0).cgColor
let colorFin = UIColor(red: 125/255, green: 195/255, blue: 226/255, alpha: 1.0).cgColor
gradientView.gradientLayer.colors = [colorInicio, colorFin]
// start/end points
gradientView.gradientLayer.startPoint = CGPoint(x: 0.0, y: 0.5)
gradientView.gradientLayer.endPoint = CGPoint(x: 1.0, y: 0.5)
}
func aplicarDegradadoDeportes() {
let colorInicio = UIColor(red: 0/255, green: 56/255, blue: 255/255, alpha: 1.0).cgColor
let colorFin = UIColor(red: 125/255, green: 195/255, blue: 226/255, alpha: 1.0).cgColor
gradientView.gradientLayer.colors = [colorInicio, colorFin]
// start/end points
gradientView.gradientLayer.startPoint = CGPoint(x: 0.0, y: 0.5)
gradientView.gradientLayer.endPoint = CGPoint(x: 1.0, y: 0.5)
}
}
Now you can keep this in cellForRowAt:
if evento?.tipo == "deportivo" {
cell.aplicarDegradadoCultural()
}
else if evento?.tipo == "cultural" {
cell.aplicarFondoDegradado()
}
else {
cell.aplicarDegradadoDeportes()
}
and your cell's will set the gradient properties and size automatically.

Make view with tableview as its subview a gradient color

I can make the view a background gradient without the tableview. When I add the tableview, I can either have the gradient view without the tableview cells visible or the tableview cells are visible with a white background. I cannot present the tableview with the cells visible and the gradient visible "underneath" it as the background.
override func viewDidLoad() {
super.viewDidLoad()
configureTableView()
setGradientBackground()
}
func setGradientBackground() {
let colorTop = UIColor(red: 83/255, green: 187/255, blue: 204/255, alpha: 1.0).cgColor
let colorBottom = UIColor(red: 64/255, green: 109/255, blue: 164/255, alpha: 1.0).cgColor
let gradientLayer = CAGradientLayer()
gradientLayer.colors = [colorTop, colorBottom]
gradientLayer.locations = [0.0, 1.0]
gradientLayer.frame = self.view.bounds
tableView.layer.insertSublayer(gradientLayer, at:0)
}
private func configureTableView() {
tableView.register(NavigationMenuTableViewCell.self, forCellReuseIdentifier: "menu")
tableView.delegate = self
tableView.dataSource = self
tableView.separatorStyle = .none
view.addSubview(tableView)
tableView.frame = CGRect(x: 0, y: 0, width: view.frame.width, height: view.frame.height)
}
class NavigationMenuTableViewCell: UITableViewCell {
private let label = UILabel()
func setup(_ buttonName: String) {
label.text = buttonName
label.font = UIFont.systemFont(ofSize: 14)
label.layer.cornerRadius = 6
label.clipsToBounds = true
label.textColor = .white
label.textAlignment = .center
label.backgroundColor = UIColor.init(displayP3Red: 50/255, green: 96/255, blue: 149/255, alpha: 1)
contentView.addSubview(label)
label.frame = CGRect(x: 20, y: 3, width: contentView.frame.width - 40, height: contentView.frame.height - 6)
}
}
You should create a separate view and set it as backgroundView for tableView.
In my case with collectionView it helped.
final class ViewController: UIViewController {
#IBOutlet weak var collectionView: UICollectionView!
override func viewDidLoad() {
super.viewDidLoad()
collectionView.dataSource = self
setGradientBackground()
}
private func setGradientBackground() {
let colorTop = UIColor(red: 83/255, green: 187/255, blue: 204/255, alpha: 1.0).cgColor
let colorBottom = UIColor(red: 64/255, green: 109/255, blue: 164/255, alpha: 1.0).cgColor
let gradientLayer = CAGradientLayer()
gradientLayer.colors = [colorTop, colorBottom]
gradientLayer.locations = [0.0, 1.0]
gradientLayer.frame = self.view.bounds
let backgroundView = UIView(frame: collectionView.bounds)
backgroundView.layer.insertSublayer(gradientLayer, at: .zero)
collectionView.backgroundView = backgroundView
}
}
extension ViewController: UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 100
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cellId", for: indexPath)
cell.backgroundColor = .white
return cell
}
}
Result

UIButtons setAttributedTitle Disappears After Calling layoutSubviews in UIButton Extension

I had a corner radius problem with all of my UIButtons, but was finally able to resolve the issue by following the solution at (Setting corner radius through viewDidAppear() or viewWillLayoutSubviews()?
) However, now I have "lost" all of my attributed button titles. I have been battling this issue for a couple of weeks and feel like I am very close to figuring it all out. I apologize if this is a poorly phrased question as I am still relatively new to Swift.
Here is the application I am working on:
my default iOS calculator project
In my Swift-file, UIButtonExtension.swift, I have the following:
import Foundation
import UIKit
extension UIButton {
override open func layoutSubviews() {
super.layoutSubviews()
let radius = min(bounds.width, bounds.height) / 2
layer.cornerRadius = radius
}
}
In one of my other Swift-files, myCalculatorViewController.swift, I have:
import UIKit
class myCalculatorViewController: UIViewController {
#IBOutlet weak var tag1_Button: UIButton!
#IBOutlet weak var tag2_Button: UIButton!
#IBOutlet weak var tag3_Button: UIButton!
// .....
#IBOutlet weak var tag19_Button: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
// main/basic calc button view controller
tag1_Button.titleLabel?.textAlignment = .center
tag1_Button.contentHorizontalAlignment = .center
tag1_Button.titleLabel?.numberOfLines = 1
let str_tag1_Button = NSMutableAttributedString(string: "AC")
str_tag1_Button.addAttribute(NSAttributedStringKey.font, value: UIFont.systemFont(ofSize: 10), range: NSMakeRange(0, 2))
str_tag1_Button.addAttribute(NSAttributedStringKey.foregroundColor, value: UIColor(red: 0/255.0, green: 0/255.0, blue: 0/255.0, alpha: 1.0), range: NSMakeRange(0, 2))
tag1_Button.setAttributedTitle(str_tag1_Button, for: .normal)
tag1_Button.backgroundColor = UIColor(red: 40/255.0, green: 247/255.0, blue: 45/255.0, alpha: 1.0)
// and so forth with the rest of the tag buttons up to tag19_Button that sets title, "="
}
}
Next, in another Swift-file, instantiatedLandscapeButtonViewController, I have a similiar setup for the UIButtons with tag1 to tag30:
import UIKit
class instantiatedLandscapeButtonViewController: UIViewController {
#IBOutlet weak var tag1_Button: UIButton!
#IBOutlet weak var tag2_Button: UIButton!
#IBOutlet weak var tag3_Button: UIButton!
// .....
#IBOutlet weak var tag30_Button: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
// additional landscape buttons, setup
tag1_Button.titleLabel?.textAlignment = .center
tag1_Button.contentHorizontalAlignment = .center
tag1_Button.titleLabel?.numberOfLines = 1
let str_tag1_Button = NSMutableAttributedString(string: "mc")
str_tag1_Button.addAttribute(NSAttributedStringKey.font, value: UIFont.systemFont(ofSize: 10), range: NSMakeRange(0, 2))
str_tag1_Button.addAttribute(NSAttributedStringKey.foregroundColor, value: UIColor(red: 251/255.0, green: 251/255.0, blue: 251/255.0, alpha: 1.0), range: NSMakeRange(0, 2))
tag1_Button.setAttributedTitle(str_tag1_Button, for: .normal)
// and so forth
}
}
Your code as it stands is dangerous and illegal:
extension UIButton {
override open func layoutSubviews() {
No! You cannot perform an override in an extension! The results can be unpredictable. The way to achieve a reliable circular button is to subclass UIButton, where override is legal, and use that subclass.
class MyCircularButton: UIButton {
override open func layoutSubviews() {
super.layoutSubviews()
let radius = min(bounds.width, bounds.height) / 2
layer.cornerRadius = radius
}
}
Now use a MyCircularButton instead of a plain UIButton wherever you want a circular button. I don't know that this will solve the issue you're having, but it is certainly a required first step.
I tested your remaining code like this, and it worked fine:
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let tag1_Button = MyCircularButton()
tag1_Button.frame = CGRect(x: 100, y: 100, width: 40, height: 40)
tag1_Button.titleLabel?.textAlignment = .center
tag1_Button.contentHorizontalAlignment = .center
tag1_Button.titleLabel?.numberOfLines = 1
let str_tag1_Button = NSMutableAttributedString(string: "AC")
str_tag1_Button.addAttribute(.font, value: UIFont.systemFont(ofSize: 10), range: NSMakeRange(0, 2))
str_tag1_Button.addAttribute(.foregroundColor, value: UIColor(red: 0/255.0, green: 0/255.0, blue: 0/255.0, alpha: 1.0), range: NSMakeRange(0, 2))
tag1_Button.setAttributedTitle(str_tag1_Button, for: .normal)
tag1_Button.backgroundColor = UIColor(red: 40/255.0, green: 247/255.0, blue: 45/255.0, alpha: 1.0)
self.view.addSubview(tag1_Button)
}
}
Result:

Segue to different categories from Collection View

Edit: I am on the right track, but the button can only point to 1 ViewController
I used
#IBAction func viewTouchedBttn(_ sender: Any) {
print("touched")
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
switch indexPath.row {
case 0:
print("1")
performSegue(withIdentifier: "1", sender: nil)
case 1:
performSegue(withIdentifier: "2", sender: nil)
case 2:
performSegue(withIdentifier: "3", sender: nil)
default:
break
}
}
I recently done the tutorial about building a carousel in swift with a UICollectionView as taught in this tutorial https://www.youtube.com/watch?v=vB-HKnhOgl8 ( you can download it as well so we would have the same basis)
I am quit new to coding so I am sorry if this is quit obvious for you and I don't get it ^^.
Each category should point to a different vc by clicking on the cell.
When I press on the View with "Travel the world" the segue should point to the VC where you can talk about Travel, if I am interested in building apps and click on that view, I want to be directed to this specific category.
Thanks for your help! :)
edit: files
InterestCollectionView
class InterestCollectionViewCell: UICollectionViewCell
{
#IBOutlet weak var featuredImageView: UIImageView!
#IBOutlet weak var interestTitleLabel: UILabel!
#IBOutlet weak var backgroundColorView: UIView!
#IBOutlet weak var kategorie: UILabel!
var interest: Interest? {
didSet {
self.updateUI()
}
}
private func updateUI()
{
if let interest = interest {
kategorie.text = interest.kategorie
featuredImageView.image = interest.featuredImage
interestTitleLabel.text = interest.title
backgroundColorView.backgroundColor = interest.color
} else {
featuredImageView.image = nil
interestTitleLabel.text = nil
backgroundColorView.backgroundColor = nil
}
}
override func layoutSubviews() {
super.layoutSubviews()
self.layer.cornerRadius = 3.0
layer.shadowRadius = 10
layer.shadowOpacity = 0.4
layer.shadowOffset = CGSize(width: 5, height: 10)
self.clipsToBounds = false
}
}
interest file
class Interest
{
// MARK: - Public API
var kategorie = ""
var title = ""
var featuredImage: UIImage
var color: UIColor
init(title: String, featuredImage: UIImage, color: UIColor, kategorie: String)
{
self.kategorie = kategorie
self.title = title
self.featuredImage = featuredImage
self.color = color
}
// MARK: - Private
// dummy data
static func fetchInterests() -> [Interest]
{
return [
Interest(title: "Travelling Around the World", featuredImage: UIImage(named: "f1")!, color: UIColor(red: 63/255.0, green: 71/255.0, blue: 80/255.0, alpha: 0.8), kategorie: "Forum"),
Interest(title: "Cafe with Best Friends", featuredImage: UIImage(named: "f2")!, color: UIColor(red: 240/255.0, green: 133/255.0, blue: 91/255.0, alpha: 0.8), kategorie: "Forum"),
Interest(title: "Study Personal Development Books and Courses", featuredImage: UIImage(named: "f3")!, color: UIColor(red: 105/255.0, green: 80/255.0, blue: 227/255.0, alpha: 0.8), kategorie: "Post"),
Interest(title: "Build Amazing iOS Apps", featuredImage: UIImage(named: "f4")!, color: UIColor(red: 102/255.0, green: 102/255.0, blue: 102/255.0, alpha: 0.8), kategorie: "Forum"),
Interest(title: "Learn. Create. Contribute.", featuredImage: UIImage(named: "f5")!, color: UIColor(red: 245/255.0, green: 62/255.0, blue: 40/255.0, alpha: 0.8),kategorie: "Forum"),
Interest(title: "Inspire, Instruct, and Empower People", featuredImage: UIImage(named: "f6")!, color: UIColor(red: 103/255.0, green: 217/255.0, blue: 87/255.0, alpha: 0.8), kategorie: "Bilder"),
Interest(title: "Business and Marketing Geeks", featuredImage: UIImage(named: "f7")!, color: UIColor(red: 63/255.0, green: 71/255.0, blue: 80/255.0, alpha: 0.8), kategorie: "Forum"),
Interest(title: "3D Printing, Virtual Reality and AI", featuredImage: UIImage(named: "f8")!, color: UIColor(red: 240/255.0, green: 133/255.0, blue: 91/255.0, alpha: 0.8), kategorie: "Forum"),
Interest(title: "Einzeiler", featuredImage: UIImage(named: "f3")!, color: UIColor(red: 30/255.0, green: 20/255.0, blue: 130/255.0, alpha: 0.8), kategorie: "Forum")
]
}
}
the interest ViewController
import UIKit
class InterestsViewController: UIViewController
{
#IBOutlet weak var collectionView: UICollectionView!
var interests = Interest.fetchInterests()
let cellScaling: CGFloat = 0.6
override func viewDidLoad() {
super.viewDidLoad()
let screenSize = UIScreen.main.bounds.size
let cellWidth = floor(screenSize.width * cellScaling)
let cellHeight = floor(screenSize.height * cellScaling)
let insetX = (view.bounds.width - cellWidth) / 2.0
let insetY = (view.bounds.height - cellHeight) / 2.0
let layout = collectionView!.collectionViewLayout as! UICollectionViewFlowLayout
layout.itemSize = CGSize(width: cellWidth, height: cellHeight)
collectionView?.contentInset = UIEdgeInsets(top: insetY, left: insetX, bottom: insetY, right: insetX)
collectionView?.dataSource = self
collectionView?.delegate = self
}
}
extension InterestsViewController : UICollectionViewDataSource
{
func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return interests.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell
{
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "InterestCell", for: indexPath) as! InterestCollectionViewCell
cell.interest = interests[indexPath.item]
return cell
}
}
extension InterestsViewController : UIScrollViewDelegate, UICollectionViewDelegate
{
func scrollViewWillEndDragging(_ scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>)
{
let layout = self.collectionView?.collectionViewLayout as! UICollectionViewFlowLayout
let cellWidthIncludingSpacing = layout.itemSize.width + layout.minimumLineSpacing
var offset = targetContentOffset.pointee
let index = (offset.x + scrollView.contentInset.left) / cellWidthIncludingSpacing
let roundedIndex = round(index)
offset = CGPoint(x: roundedIndex * cellWidthIncludingSpacing - scrollView.contentInset.left, y: -scrollView.contentInset.top)
targetContentOffset.pointee = offset
}
}
You have multiple options to do what you want.
For example you could add in your storyboard a storyboard reference to controller you want to segue to, or a view controller if it's in the same storyboard. And then ctrl + drag from the view to the view controller (or storyboard reference) that you want to segue to. There you will have the different segues types (show, push, etc).
That's the full storyboard way of doing it.
There are multiple other options. But that may be the easiest.
https://developer.apple.com/library/content/featuredarticles/ViewControllerPGforiPhoneOS/UsingSegues.html
EDIT:
You can also create 8 segues from the controller (ctrl + drag from controller) to other controllers or storyboard references. Then click on the segues created and in the identifier inspector name every segue with a unique identifier.
Then when you click on the cell you can determine which cell was clicked and perform the segue you need for that cell with performSegueWithIdentifier(identifier, sender)

UIView is not changing correctly the color values SWIFT

I want my app to start with a color in the view but when I add the UIColor values to the ViewDidLoad I change the color to white! and not the red color I want to add. Here is my code, I have checked all the code but am kind of programming in swift so I don't find something that is not getting the work done:
class RGBViewController: UIViewController {
//Sldiers
#IBOutlet weak var redSlider: UISlider!
#IBOutlet weak var greenSlider: UISlider!
#IBOutlet weak var blueSlider: UISlider!
//Labels
#IBOutlet weak var redLabel: UILabel!
#IBOutlet weak var greenLabel: UILabel!
#IBOutlet weak var blueLabel: UILabel!
//View
#IBOutlet weak var colorView: UIView!
//set the thumb image
func changeThumbImage() {
let redThumb = UIImage(named: "RedSmall")
redSlider?.setThumbImage(redThumb, forState: .Normal)
let greenThumb = UIImage(named: "GreenSmall")
greenSlider?.setThumbImage(greenThumb, forState: .Normal)
let blueThumb = UIImage(named: "BlueSmall")
blueSlider?.setThumbImage(blueThumb, forState: .Normal)
}
//VIEW DID LOAD
override func viewDidLoad() {
super.viewDidLoad()
changeThumbImage()
updateBackgroundColor()
colorView.backgroundColor! = UIColor(red: 226, green: 67, blue: 67, alpha: 1)
}
func colorValues() {
//assign the Int value to the labels
redLabel?.text = String(stringInterpolationSegment: Int(redSlider.value * 255))
greenLabel?.text = String(stringInterpolationSegment: Int(greenSlider.value * 255))
blueLabel?.text = String(stringInterpolationSegment: Int(blueSlider.value * 255))
}
#IBAction func updateBackgroundColor() {
colorValues()
//safe unwrap the sliders and assign the view color
if let red = redSlider, green = greenSlider, blue = blueSlider{
let redValue = CGFloat(red.value)
let greenValue = CGFloat(green.value)
let blueValue = CGFloat(blue.value)
colorView.backgroundColor = UIColor(red: redValue, green: greenValue, blue: blueValue, alpha: 1)
}
}
}
You have to divide the color value with 255
UIColor(red: 226/255.0, green: 67/255.0, blue: 67/255.0, alpha: 1.0)
With your action also :
#IBAction func updateBackgroundColor() {
colorValues()
let redValue = CGFloat(redSlider.value)
let greenValue = CGFloat(greenSlider.value)
let blueValue = CGFloat(blueSlider.value)
colorView.backgroundColor = UIColor(red: redValue/255.0, green: greenValue/255.0, blue: blueValue/255.0, alpha: 1.0)
}
I have created sample :
#IBOutlet var colorView: UIView!
#IBAction func chageSlider(sender: UISlider!) {
println(sender.value)
self.colorView.backgroundColor = UIColor(red: CGFloat(sender.value)/255.0, green: 0.0, blue: 0.0, alpha: 1.0)
}
changeSlider is valueChanged action of the UISlider
Connect your slider with #IBAction
Hope it helps you.