tableview cell has wrong background layer after reuse - ios

I have a UIView extension which makes a gradient background from two colours. I use this so I add a nice background to my custom tableView cells. But after the reuse, the colour is always wrong (unlike the data inside which is correct). It's not like a plain background colour, and all colors depend on the value from the fetched data. After reuse, the background is always random from the previously generated cells (and their backgrounds).
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "tableViewCell", for: indexPath) as! TableViewCell
var imgTitle = ""
var color = UIColor()
let title = fetchedUV[indexPath.row].value
if title > 11 {
imgTitle = "flame"
color = UIColor.purple
cell.setGradientBackground(colorOne: .white, colorTwo: color)
} else if title >= 8 {
imgTitle = "sun-protection"
color = UIColor.red
cell.setGradientBackground(colorOne: .white, colorTwo: color)
} else if title >= 6 {
imgTitle = "sunbed"
color = UIColor.orange
cell.setGradientBackground(colorOne: .white, colorTwo: color)
} else if title >= 3 {
imgTitle = "sunglasses"
color = UIColor.yellow
cell.setGradientBackground(colorOne: .white, colorTwo: color)
} else {
imgTitle = "ok"
color = UIColor.green
cell.setGradientBackground(colorOne: .white, colorTwo: color)
}
colors.append(color)
let UVValue = String(describing: title)
cell.backgroundColor = UIColor.orange
cell.commonInit(imgTitle, title: UVValue, time: fetchedUV[indexPath.row].dateIso)
cell.logoImage.layer.cornerRadius = (cell.frame.height) / 2
cell.layer.cornerRadius = cell.frame.height/2
cell.layer.masksToBounds = true
//cell.setGradientBackground(colorOne: .white, colorTwo: color)
return cell
}
extension UIView {
func setGradientBackground(colorOne: UIColor, colorTwo: UIColor) {
let gradientLayer = CAGradientLayer()
gradientLayer.frame = bounds
gradientLayer.colors = [colorOne.cgColor, colorTwo.cgColor]
gradientLayer.locations = [0.0, 1.0]
gradientLayer.startPoint = CGPoint(x: 0.0, y: 0.0)
gradientLayer.endPoint = CGPoint(x: 1.0, y: 1.0)
layer.insertSublayer(gradientLayer, at: 0)
}
}

Just for an Example try looking at this
extension UIView
{
//This func will add gradient backgroung
//Just sample one
func setGradientBackground()
{
//Colors
let colorTop = UIColor(red: 255.0/255.0, green: 149.0/255.0, blue: 0.0/255.0, alpha: 1.0).cgColor
let colorBottom = UIColor(red: 255.0/255.0, green: 94.0/255.0, blue: 58.0/255.0, alpha: 1.0).cgColor
//Set Gradient layer
let gradientLayer = CAGradientLayer()
//Colors
gradientLayer.colors = [ colorTop, colorBottom]
//Locations
gradientLayer.locations = [ 0.0, 1.0]
//Here is the main Play
//Set Layer name so can be identified while Dequeuing cell
gradientLayer.name = "layerName"
//Set bounds
gradientLayer.frame = self.layer.bounds
//Insert Layer
self.layer.addSublayer(gradientLayer)
}
}
Now in CellForRowAt of TableView
//Setting cell
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
//Get all the sublayers of cell
for sublayer in cell.layer.sublayers!
{
//Check that sublayer is Already Added or not
if sublayer.name == "layerName"
{
//Sublayer already added
//Print already Added
print("Cell Deque again")
}
else
{
//Sublayer is not added yet
//Time to add Gradient Background
cell.setGradientBackground()
print("Layer Added")
}
}
//setting title
cell.textLabel?.text = items[indexPath.section][indexPath.row]
return cell
}
Hope it Helps , You can Name a layer that is being added as SubLayer and when Adding it to Cell as it gets Deque again and again so you must see that layer is not override on previous added layer

I had find and remove the previously added layer (the CAGradientLayer because it can remove any other layer as well). Do the checks and add another layer if its needed. I also changed the function so the layer now has a name. (thanks to iOS Geek for the suggestion)
for sublayer in cell.layer.sublayers! {
if let _ = sublayer as? CAGradientLayer {
if sublayer.name == name {
print("Cell deque again")
} else {
sublayer.removeFromSuperlayer()
cell.setGradientBackground0(colorOne: .white, colorTwo: color, name: name)
}
} else {
cell.setGradientBackground0(colorOne: .white, colorTwo: color, name: name)
}
}
extension UIView {
func setGradientBackground0(colorOne: UIColor, colorTwo: UIColor, name: String) {
let gradientLayer = CAGradientLayer()
gradientLayer.frame = bounds
gradientLayer.colors = [colorOne.cgColor, colorTwo.cgColor]
gradientLayer.locations = [0.0, 1.0]
gradientLayer.startPoint = CGPoint(x: 0.0, y: 0.0)
gradientLayer.endPoint = CGPoint(x: 1.0, y: 1.0)
gradientLayer.name = name
layer.insertSublayer(gradientLayer, at: 0)
}
}
I'll leave this just in case.

Related

UISearchBar with a white background is impossible?

I really thought it would be easy to set the background color of my UISearchBar's text field to white. But no matter what I try, it always stays offwhite / light gray (#efeff0).
import UIKit
class ViewController: UIViewController {
private let searchController = UISearchController()
override func viewDidLoad() {
super.viewDidLoad()
navigationItem.title = "Hello World"
view.backgroundColor = #colorLiteral(red: 0.9588784575, green: 0.9528519511, blue: 0.9350754619, alpha: 1)
searchController.searchBar.searchTextField.backgroundColor = .white
navigationItem.searchController = searchController
}
}
How can I make the search bar have a pure white background color? App is iOS 13+, if that helps.
Tiny test project: https://github.com/kevinrenskers/WhiteSearch.
It's possible. Set the background of the search field with a white image.
let size = CGSize(width: searchController.searchBar.frame.size.width - 12, height: searchController.searchBar.frame.size.height - 12)
let backgroundImage = createWhiteBG(size)!
let imageWithCorner = backgroundImage.createImageWithRoundBorder(cornerRadiuos: 10)!
searchController.searchBar.setSearchFieldBackgroundImage(imageWithCorner, for: UIControl.State.normal)
If you don't want to input an image to app. Try this for create one programmatically.
func createWhiteBG(_ frame : CGSize) -> UIImage? {
var rect = CGRect(x: 0, y: 0, width: 0, height: 0)
rect.size = frame
UIGraphicsBeginImageContext(rect.size)
let context = UIGraphicsGetCurrentContext()
context?.setFillColor(UIColor.white.cgColor)
context?.fill(rect)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image
}
extension UIImage {
func createImageWithRoundBorder(cornerRadiuos : CGFloat) -> UIImage? {
UIGraphicsBeginImageContextWithOptions(self.size, false, scale)
let rect = CGRect(origin:CGPoint(x: 0, y: 0), size: self.size)
let context = UIGraphicsGetCurrentContext()
let path = UIBezierPath(
roundedRect: rect,
cornerRadius: cornerRadiuos
)
context?.beginPath()
context?.addPath(path.cgPath)
context?.closePath()
context?.clip()
self.draw(at: CGPoint.zero)
context?.restoreGState()
path.lineWidth = 1.5
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image
}
}
Try this ... Change colors and images according to your preference
DispatchQueue.main.async {
searchBar.backgroundImage = UIImage()
for s in searchBar.subviews[0].subviews {
if s is UITextField {
s.layer.borderWidth = 1.0
s.layer.borderColor = UIColor.lightGray.cgColor
}
}
let searchTextField:UITextField = searchBar.subviews[0].subviews.last as? UITextField ?? UITextField()
searchTextField.layer.cornerRadius = 10
searchTextField.textAlignment = NSTextAlignment.left
let image:UIImage = UIImage(named: "search")!
let imageView:UIImageView = UIImageView.init(image: image)
searchTextField.leftView = nil
searchTextField.placeholder = "Search..."
searchTextField.font = UIFont.textFieldText
searchTextField.rightView = imageView
searchTextField.rightViewMode = UITextField.ViewMode.always
}
Here is My complete Custom Search Bar Which you can define the searchbar backgroundColor and TextField background Color
Tested
import Foundation
class SearchBar: UISearchBar {
override init(frame: CGRect) {
super.init(frame: frame)
makeUI()
}
required init?(coder: NSCoder) {
super.init(coder: coder)
makeUI()
}
private func makeUI( ) {
//SearchBar BackgroundColor
self.backgroundImage = UIImage(color: UIColor.white)
//Border Width
self.layer.borderWidth = 1
//Border Color
self.layer.borderColor = UIColor("DEDEDE")?.cgColor
//Corner Radius
self.layer.cornerRadius = 3
self.layer.masksToBounds = true
//Change Icon
self.setImage(UIImage(named: "search")?
.byResize(to: CGSize(width: 30, height: 30)), for: .search, state: .normal)
if let searchTextField = self.value(forKey: "searchField") as? UISearchTextField {
//TextField Background !!!!!
searchTextField.backgroundColor = UIColor.white
//TextField Font
searchTextField.font = UIFont(name: "Poppins-Regular", size: 21)
searchTextField.textColor = .black
}
}
}

Button Not Fully Drawn

I have a button with text and an image on it. It gets set up in viewDidAppear and then in the IBAction I change the Attributed title. For some reason the button background color doesn't completely cover the button on the initial draw. It leaves a horizontal sliver of white. I found that by running my formatButton function in the IBAction subsequent button presses show a properly drawn button. But I can't get the first loaded view of the button to look right. Any ideas?
I found that by formatting in the IBAction it fixed it for future button draws but a sendAction(.touchUpInside) couldn't even fake it into fixing the draw problem. (It did change the button text like the IBAction makes it though.)
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
formatButton(btn: searchTitlesButton)
formatButton(btn: searchPeopleButton)
formatButton(btn: searchCategoryButton)
searchTitlesButton.setTitle("Title", for: .normal)
searchPeopleButton.setTitle("Actor", for: .normal)
//searchCategoryButton.setTitle(categoryList[searchCategoryIndex], for: .normal)
let fullString = NSMutableAttributedString()
let imageAttachment = NSTextAttachment()
imageAttachment.image = UIImage(named:"DownArrow")
let imageString = NSAttributedString(attachment: imageAttachment)
fullString.append(NSAttributedString(string: categoryList[searchCategoryIndex]+" "))
fullString.append(imageString)
searchCategoryButton.setAttributedTitle(fullString, for: .normal)
formatButton(btn: searchCategoryButton)
postTableView.rowHeight = CGFloat(120)
}
#IBAction func searchCategoryButton(_ sender: Any) {
if searchCategoryIndex < categoryList.count - 1 {
searchCategoryIndex += 1
} else {
searchCategoryIndex = 0
}
// Going to try and make a formatted label with a string and image of a down arrow.
let fullString = NSMutableAttributedString()
let imageAttachment = NSTextAttachment()
imageAttachment.image = UIImage(named:"DownArrow")
let imageString = NSAttributedString(attachment: imageAttachment)
fullString.append(NSAttributedString(string: categoryList[searchCategoryIndex]+" "))
fullString.append(imageString)
searchCategoryButton.setAttributedTitle(fullString, for: .normal)
formatButton(btn: searchCategoryButton)
}
func formatButton(btn:UIButton) {
btn.layer.cornerRadius = 5
btn.layer.borderWidth = 1
btn.layer.borderColor = UIColor.black.cgColor
btn.setTitleColor(UIColor.white, for: .normal)
btn.titleLabel?.font = UIFont.systemFont(ofSize: 14, weight: UIFont.Weight.bold)
let gradientLayer = CAGradientLayer()
gradientLayer.frame = btn.bounds
let bottomColor = UIColor(red: CGFloat(25/255.0), green: CGFloat(113/255.0), blue: CGFloat(255/255.0), alpha: CGFloat(1.0))
gradientLayer.colors = [UIColor.white.cgColor, bottomColor.cgColor]
btn.layer.insertSublayer(gradientLayer, at: 0)
btn.clipsToBounds = true
}
The reason why the background gradient doesn't fully cover the button, it probably because the size of the button changes when you set the attributed title. The best way to solve this, is by creating a subclass of UIButton, so that you can update the frame of your custom gradient layer, whenever the button's bounds change. For example:
class GradientButton: UIButton {
private let gradientLayer = CAGradientLayer()
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setup()
}
private func setup() {
layer.cornerRadius = 5
layer.borderWidth = 1
layer.borderColor = UIColor.black.cgColor
setTitleColor(UIColor.white, for: .normal)
titleLabel?.font = UIFont.systemFont(ofSize: 14, weight: UIFont.Weight.bold)
let bottomColor = UIColor(red: CGFloat(25/255.0), green: CGFloat(113/255.0), blue: CGFloat(255/255.0), alpha: CGFloat(1.0))
gradientLayer.colors = [UIColor.white.cgColor, bottomColor.cgColor]
layer.insertSublayer(gradientLayer, at: 0)
clipsToBounds = true
}
override var bounds: CGRect {
didSet {
gradientLayer.frame = layer.bounds
}
}
}
Then in the storyboard of nib you can change the class of the button to GradientButton. It should now automatically apply the gradient styling, and update the frame whenever the bounds of the button change.
I hope you find this useful. Let me know if you are still having issues.

Button gradient not working when added to viewDidLayoutSubviews

I am adding a button gradient using the below code
extension UIView {
func applyGradient(colors: [UIColor]) {
self.applyGradient(colors: colors, locations: nil)
}
func applyGradient(colors: [UIColor], locations: [NSNumber]?) {
let gradient = CAGradientLayer()
gradient.frame = self.bounds
gradient.colors = colors.map { $0.cgColor }
gradient.locations = locations
gradient.startPoint = CGPoint(x: 0, y: 0)
gradient.endPoint = CGPoint(x: 1, y: 0)
self.layer.insertSublayer(gradient, at: 0)
}
}
Calling initStyle() in viewDidLayoutSubviews() is not working.
func initStyle() {
submitBtn.applyGradient(colors: [#colorLiteral(red: 0.1176470588, green: 0.3882352941, blue: 0.5254901961, alpha: 1), #colorLiteral(red: 0.2941176471, green: 0.9098039216, blue: 0.9529411765, alpha: 1)])
submitBtn.layer.cornerRadius = 15.0
submitBtn.layer.masksToBounds = true
}
I am creating all UI elements programatically. I had constraints setup properly and is working.
lazy var submitBtn: UIButton = {
let btn = UIButton(type: .system)
btn.translatesAutoresizingMaskIntoConstraints = false
btn.setTitle("SUBMIT", for: .normal)
return btn
}()
How to make this working?
The gradient display only if I place initStyle() in viewDidAppear() and not in viewDidLayoutSubviews(), which is creating a delay in displaying the button gradient. I want to avoid this delay. So I am adding it in viewDidLayoutSubviews, but then the gradient does not appear.
I think the problem here is that self.bounds is 0 at the point you are calling your gradient function. Try calling it at a later time, for example viewWillAppear or call view.layoutSubViews to trigger iewDidLayoutSubviews()
lazy var submitBtn: UIButton = {
let btn = UIButton(type: .custom) //Set custom instead of system
btn.translatesAutoresizingMaskIntoConstraints = false
btn.setTitle("SUBMIT", for: .normal)
return btn
}()
try using the function inside
viewWillAppeare()
Also why not apply the gradient into the button from the start without a separated function? that will make the button appears w\ the gradient already builtin.
if you want to set the gradient w\ a condition you could use the following
func displayButton(condition: Bool){
lazy var submitBtn: UIButton = {
let btn = UIButton(type: .system)
btn.translatesAutoresizingMaskIntoConstraints = false
btn.setTitle("SUBMIT", for: .normal)
if condition == true {
//set the gradient here
return btn
} else if condition == false
return btn
}
}()
override func viewDidLoad(){
super.viewDidLoad()
//here you can set the condition to show the gradient or not depending on what you want
displayButton(true) //will show the gradient
displayButton(false) // will show without gradient
}
I can't test this code at the moment so i'm not sure about it, give it a try.

Swift Table View Cell changes gradient Color after scrolling

I just realized that my table view is not working correctly, after checking my App on multiple devices. I am currently working on a View that contains a Scroll View at the top, and an TableView at the bottom.
When I was creating the View I was working with an Iphone XS Max as my testing device, and everything worked fine. However, when the device gets smaller the Table View starts to do weird things.
Thats what I want the table view to look like:
Table View on Iphone XS Max
On smaller devices the background color of the last table view cell is not green (what it should be according to code), instead it has the same color as the first cell.
When I scroll back to the top, the first cell has the color the last cell should have according to my code
Here is my cellForRowAt IndexPath
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "GruppenCell", for: indexPath) as! GroupCell
cell.bgView.backgroundColor = nil
cell.bgView.layer.cornerRadius = 10
cell.bgView.clipsToBounds = true
cell.selectionStyle = .none
if(indexPath.row == 0) {
cell.bgView.setGradientBackground(colorOne: UIColor.white
, colorTwo: KitaGruppen.Spatzen().color, bounds_object: cell.bgView)
cell.groupLabel!.text = "Spatzen"
cell.iconImageView?.image = UIImage(named: "SpatzIcon")
}
else if(indexPath.row == 1) {
cell.bgView.setGradientBackground(colorOne: UIColor.white
, colorTwo: KitaGruppen.Elefanten().color, bounds_object: cell.bgView)
cell.groupLabel!.text = "Elefanten"
cell.iconImageView?.image = UIImage(named: "elefantIcon")
}
else if(indexPath.row == 2) {
cell.bgView.setGradientBackground(colorOne: UIColor.white
, colorTwo: KitaGruppen.Mäuse().color, bounds_object: cell.bgView)
cell.groupLabel!.text = "Mäuse"
cell.iconImageView?.image = UIImage(named: "mouseIcon")
}
else if(indexPath.row == 3) {
cell.bgView.setGradientBackground(colorOne: UIColor.lightGray
, colorTwo: KitaGruppen.Pferde().color, bounds_object: cell.bgView)
cell.groupLabel!.text = "Pferde"
cell.iconImageView?.image = UIImage(named: "horseIcon")
print("Ich bin der Pferd Index")
}
else if(indexPath.row == 4) {
cell.bgView.setGradientBackground(colorOne: UIColor.lightGray
, colorTwo: KitaGruppen.Frösche().color, bounds_object: cell.bgView)
cell.groupLabel!.text = "Frösche"
cell.iconImageView?.image = UIImage(named: "FrogIcon")
}
else {
cell.bgView.setGradientBackground(colorOne: UIColor.lightGray
, colorTwo: UIColor.white, bounds_object: cell.bgView)
}
return cell
}
Here is my Struct for the colors
struct KitaGruppen {
struct Spatzen{
var name = "Spatzen"
var name_lower = "spatzen"
var color = #colorLiteral(red: 1, green: 0.871347487, blue: 0, alpha: 1)
}
struct Elefanten{
var name = "Elefanten"
var name_lower = "Elefanten"
var color = #colorLiteral(red: 0, green: 0.3798098862, blue: 1, alpha: 1)
}
struct Pferde{
var name = "Pferde"
var name_lower = "pferde"
var color = #colorLiteral(red: 1, green: 0, blue: 0, alpha: 1)
}
struct Frösche{
var name = "Frösche"
var name_lower = "frösche"
var color = #colorLiteral(red: 0.5412063003, green: 0.9987080693, blue: 0.2685243189, alpha: 1)
}
struct Mäuse{
var name = "Mäuse"
var name_lower = "Mäuse"
let color = #colorLiteral(red: 0.9411764741, green: 0.4980392158, blue: 0.3529411852, alpha: 1)
}
}
Here is my Cell Class
class GroupCell: UITableViewCell {
override func prepareForReuse() {
super.prepareForReuse()
self.iconImageView.image = nil
self.groupLabel.text = ""
self.bgView.setGradientBackground(colorOne: UIColor.white
, colorTwo: KitaGruppen.Spatzen().color, bounds_object: self.bgView)
}
I added the prepareForReuse Method to fix this error, but it did not have any affects.
I dont know if it is important, but here is my setGradientBackground Method:
func setGradientBackground(colorOne: UIColor, colorTwo: UIColor, bounds_object: UIView){
let gradientLayer = CAGradientLayer()
gradientLayer.frame = bounds_object.bounds
gradientLayer.colors = [colorOne.cgColor, colorTwo.cgColor]
gradientLayer.locations = [0.0, 1.0]
gradientLayer.startPoint = CGPoint(x: 1.0, y: 1.0)
gradientLayer.endPoint = CGPoint(x: 0.0, y: 0.0)
layer.insertSublayer(gradientLayer, at: 0)
}
The weird thing is that the only cell data that has this bug is the gradient color. The text for the text label, and also the icons don't get mixed up at all.
Does anybody know any fix for this ?
Thanks for your help!
The issue could be caused by the fact that a new gradient layer is inserted every time setGradientBackground is called.
To avoid that check if the layer exists. If it exists update the colors otherwise create the new layer.
func setGradientBackground(colorOne: UIColor, colorTwo: UIColor, bounds_object: UIView){
if let gradientLayer = layer.sublayers?.first as? CAGradientLayer {
gradientLayer.colors = [colorOne.cgColor, colorTwo.cgColor]
} else {
let gradientLayer = CAGradientLayer()
gradientLayer.frame = bounds_object.bounds
gradientLayer.colors = [colorOne.cgColor, colorTwo.cgColor]
gradientLayer.locations = [0.0, 1.0]
gradientLayer.startPoint = CGPoint(x: 1.0, y: 1.0)
gradientLayer.endPoint = CGPoint(x: 0.0, y: 0.0)
layer.insertSublayer(gradientLayer, at: 0)
}
}
Actually prepareForReuse() is redundant because you can set image and text in the last else scope. It makes sure that all UI elements are set to a defined state.
Add these two lines and delete the entire prepareForReuse() method in GroupCell.
else {
cell.bgView.setGradientBackground(colorOne: UIColor.lightGray
, colorTwo: UIColor.white, bounds_object: cell.bgView)
cell.iconImageView.image = nil
cell.groupLabel.text = ""
}
A better syntax than if - else if in this case is a switch
switch indexPath.row {
case 0:
cell.bgView.setGradientBackground(colorOne: UIColor.white
, colorTwo: KitaGruppen.Spatzen().color, bounds_object: cell.bgView)
cell.groupLabel!.text = "Spatzen"
cell.iconImageView?.image = UIImage(named: "SpatzIcon")
case 1:
cell.bgView.setGradientBackground(colorOne: UIColor.white
, colorTwo: KitaGruppen.Elefanten().color, bounds_object: cell.bgView)
cell.groupLabel!.text = "Elefanten"
cell.iconImageView?.image = UIImage(named: "elefantIcon")
...
default:
cell.bgView.setGradientBackground(colorOne: UIColor.lightGray
, colorTwo: UIColor.white, bounds_object: cell.bgView)
cell.iconImageView.image = nil
cell.groupLabel.text = ""
}

Translucent white covering my button in UITableView

I've set constraints and everything but there's a translucent white "screen" covering the lower part of my screen. It's not fixed to my tableview because when I scroll down the button gets pulled up and is visible but the screen stays there. At first I thought it was a rogue view but it's not so I'm not sure what's going on. Any pointers on what I should be looking at to solve this problem? Here's a picture:
Here is my code (a little untidy because this is my first project in swift):
import UIKit
class MainViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
#IBOutlet weak var buttonView: UIView!
#IBOutlet weak var button: UIButton!
#IBOutlet weak var tableView: UITableView!
let manager = WorkoutDataSource()
let gradientLayer = CAGradientLayer()
var workouts = []
override func viewDidLoad() {
super.viewDidLoad()
self.tableView.delegate = self
self.tableView.dataSource = self
self.workouts = manager.getWorkOuts()
let borderAlpha : CGFloat = 0.7
let cornerRadius : CGFloat = 5.0
button.backgroundColor = UIColor.clearColor()
button.layer.borderWidth = 1.0
button.layer.borderColor = UIColor(white: 1.0, alpha: borderAlpha).CGColor
button.layer.cornerRadius = cornerRadius
let heightOfVisibleTableViewArea = tableView.bounds.height - topLayoutGuide.length - bottomLayoutGuide.length
let numberOfRows = tableView.numberOfRowsInSection(0)
tableView.rowHeight = heightOfVisibleTableViewArea / CGFloat(numberOfRows)
let color1 = UIColor(hue: 0.9528, saturation: 0.4, brightness: 1, alpha: 1.0) /* #ff759d */
let color2 = UIColor(hue: 0.0167, saturation: 0.25, brightness: 0.95, alpha: 1.0) /* #ffb1b1 */
let color3 = UIColor(hue: 0.2528, saturation: 0.11, brightness: 0.85, alpha: 1.0) /* #f3bbb4 */
let color4 = UIColor(hue: 0.3833, saturation: 0.21, brightness: 0.91, alpha: 1.0) /* #cedbc2 */
let color5 = UIColor(hue: 0.4417, saturation: 0.62, brightness: 0.97, alpha: 1.0) /* #b7eac7 */
let color6 = UIColor(hue: 0.4528, saturation: 0.91, brightness: 0.81, alpha: 1.0) /* #12d19e */ /* #5ef9c3 */
//let color7 = UIColor(hue: 0.5833, saturation: 0.7, brightness: 0.68, alpha: 1.0) /* #346fae */
let color7 = UIColor.flatNavyBlueColorDark()
gradientLayer.colors = [color1, color2, color3, color4, color5, color6, color7]
view.backgroundColor = UIColor.flatNavyBlueColorDark()
setTableViewBackgroundGradient(color7, bottomColor: color1)
self.navigationController?.navigationBar.backgroundColor = UIColor.flatNavyBlueColorDark()!
// Do any additional setup after loading the view, typically from a nib.
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int{
return self.workouts.count
}
func setTableViewBackgroundGradient(topColor: UIColor, bottomColor: UIColor){
let gradientBackgroundColors = [topColor.CGColor, bottomColor.CGColor]
let gradientLocations = [0.0,1.0]
let gradientLayer = CAGradientLayer()
gradientLayer.colors = gradientBackgroundColors
gradientLayer.locations = gradientLocations
gradientLayer.frame = tableView.bounds
let backgroundView = UIView(frame: tableView.bounds)
backgroundView.layer.insertSublayer(gradientLayer, atIndex: 0)
tableView.backgroundView = backgroundView
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell{
let workout = self.workouts[indexPath.row] as? Workout
let cell = tableView.dequeueReusableCellWithIdentifier("Cell") as? WorkoutCell
cell!.textCellLabel?.text = workout?.title
cell!.backgroundColor = workout?.color
cell!.countLabel.text = "\(indexPath.row+1)"
cell!.selectionStyle = UITableViewCellSelectionStyle.None
cell!.backgroundColor = UIColor.clearColor()
return cell!
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if(segue.identifier == "detailview"){
let cell = sender as? WorkoutCell
let indexPath = tableView.indexPathForCell(cell!)
let nvc = segue.destinationViewController as? UINavigationController
if let tmp = workouts[indexPath!.row] as? Workout{
let dvc = nvc?.topViewController as! DetailViewController
dvc.workout = tmp
}
}
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
self.tableView.contentInset = UIEdgeInsetsMake(0,0,55,0)
}
}

Resources