Cell runs out of tableview iOS 10 - ios

I implement the table view on the right. And as u can see, the cells go out the table view. (It even runs all the way down to the bottom)
I have tried set cell cliptoBounds = true but doesn't work
var boxes = ["Box 1", "Box 2", "Box 3", "Box 4", "Box 5"]
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = self.historyTableViewOutlet.dequeueReusableCell(withIdentifier: "HistoryCell", for: indexPath) as! HistoryVC
cell.boxName.text = boxes[indexPath.row]
return cell
}
In the HistoryVC: `class HistoryVC: UITableViewCell {
//MARK: Outlets
#IBOutlet weak var placeholderView: UIView!
#IBOutlet weak var boxName: UILabel!
}
Is there anything wrong?

What you are trying to do is to create a UIView for section header.
First: make sure your tableView in the Main Storyboard is declared with type Plain.
Second: implement 2 methods of TableViewDelegate
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let header = UIView(frame: CGRect(x: self.tableView.frame.minX, y: self.tableView.frame.minY, width: self.tableView.frame.size.width, height: 28))
let label = UILabel(frame: header.frame)
header.addSubview(label)
label.text = "SECTION HEADER"
label.textAlignment = .center
label.backgroundColor = UIColor(red: 0/255, green: 230/255, blue: 255/255, alpha: 0.9)
return header
}
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 28
}
Sure you will want to customize that view for various sections. Just switch inside the delegate method between section numbers and assign views/text/labels/colors at your choice.
Once you scroll through cells within 1 section, its header will be glued to the top layout border.
PS After new details: you should put a constraint to clip the tableView to the top layout border. Cells do not run away from a tableView. They are scrolled up, beyond the visible zone, within the scrollView that contains the tableView. Just put exact constraints to fix the position of the tableView. Here:

Try to give your table's border some color so you can see the changing. Then try cliptobonds property of tableview not cell as you said in query.

Related

Swift TableView Population

I have a tableview controller, that I am designing using Storyboard. The prototype cell is very basic, it just has two labels. A name label, and a date label.
When I run my program, the style is there (font, etc.), but it seems like the constraints aren't working? Also, the cell color doesn't show (only the tableview background shows), and the cell dividers are missing. The labels overlap each other, and when I set the cell height to 75, it doesn't appear that tall.
This is what my cell looks like compiled:
See tableview here
I made a model for the table view cell as shown here (IdeaCell is properly set on the prototype cell in storyboard):
class IdeaCell: UITableViewCell {
#IBOutlet weak var ideaNameLbl: UILabel!
#IBOutlet weak var ideaDateLbl: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
if selected {
self.layer.backgroundColor = UIColor(white: 1, alpha: 0.2).cgColor
} else {
self.layer.backgroundColor = UIColor.clear.cgColor
}
}
func configureCell(idea : CoreIdea) {
let name = idea.name
ideaNameLbl.text = name
let date = idea.date
ideaDateLbl.text = date
}
}
And my tableview view controller relevant code is here (reuse identifier (ideaCell) is properly set on the prototype cell in storyboard):
class IdeaVC: UITableViewController {
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if let cell = tableView.dequeueReusableCell(withIdentifier: "ideaCell", for: indexPath) as? IdeaCell {
let idea = ideas[indexPath.row]
cell.configureCell(idea: idea)
return cell
} else {
return UITableViewCell()
}
}
}
UPDATE:
After adding the heightForRowAt function, my cells are the proper height, and constraints are working as they should be. For some reason the cell background color is missing, and the cell divider is not appearing (the font, and font color work). They were all set in the storyboard.
Here is a screenshot of my cells:
missing cell style
UPDATE 2:
I set the divider and background like this:
self.tableView.backgroundColor = UIColor.black
self.tableview.separatorColor = UIColor.white
Hope this helps someone! I honestly don't know why my values from storyboard didn't work, but setting them in the viewDidLoad worked great.
Have you told your tableview the height of the tableviewcell? If not try this. Its one of your tableviews delegate methods.
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 75.0 //Set your cell height that you want to appear in your tableview
}
i think you must override the number of Item , and height for row at function. and set the constraint on UITableViewCell between name and date label.

UITableView & UICollectionView ? Help needed

all. I can't figure out this one.
I'm working on an app that needs to have this view as a TableView (representing excercises, with the excercise name as header) and inside each cell I need to see and be able to touch these rounded buttons (representing sets as number of buttons and reps as number inside the buttons).
I've been able to put images and that in CollectionView but no clue for buttons. Here is a sketch I've made.
https://i.imgur.com/ZjHDM4d.png
My tableViewController
import Foundation
import UIKit
class WorkoutViewController: UITableViewController {
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = #colorLiteral(red: 0.2156862745, green: 0.368627451, blue: 0.5921568627, alpha: 1)
}
var workouts: [Workout1] = Workout1.fetchWorkout1()
override func numberOfSections(in tableView: UITableView) -> Int {
return workouts.count
}
override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return "ExcerciseName"
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return workouts.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "workoutCell", for: indexPath)
let workout = workouts[indexPath.row]
cell.textLabel?.text = workout.excerciseName
cell.textLabel?.textColor = UIColor.white
return cell
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let workout = workouts[indexPath.row]
tableView.deselectRow(at: indexPath, animated: true)
print("Do \(workout.sets) sets of \(workout.reps) reps of \(workout.excerciseName)")
}
override func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
cell.backgroundColor = UIColor.clear
}
}
The source of the data
struct Workout1 {
let excerciseName: String
let sets: Int
let reps: Int
static func fetchWorkout1() -> [Workout1] {
let w1 = Workout1(excerciseName: "Bench Press", sets: 3, reps: 8)
let w2 = Workout1(excerciseName: "Push Press", sets: 3, reps: 8)
let w3 = Workout1(excerciseName: "Squat", sets: 3, reps: 8)
let w4 = Workout1(excerciseName: "Deadlift", sets: 3, reps: 8)
let w5 = Workout1(excerciseName: "Bicep Curl", sets: 3, reps: 8)
let w6 = Workout1(excerciseName: "Tricep Pushdown", sets: 3, reps: 8)
return [w1,w2,w3,w4,w5,w6]
}
}
Theoretically, based on your image, if the circles in each row do not need to be in a scroll view (there is no space to display all circles), then using UIStackView would be a good choice because stack views handle the spacing and the distribution for the circles.
On the other hand, if the view container has to be scrollable, using a collection view might covers your need.
ios 8 Swift - TableView with embedded CollectionView.
Multiple Collection View in UITableView.
You need to use a UIButton which allows you to set images and titles for each state (normal, selection, highlighted, disabled). You can do your circle buttons with that very easily.
Here you have a tutorial on how to do it:
UIButton tutorial
and the apple reference:
UIButton Apple doc
Note that you don't need an image for drawing a circle button, for a simple one you can add a border to your button and set its layer's cornerRadius property to be a circle.
For your layout, your can do it with a UICollectionView by setting correctly the size of the header (supplementary view) and cells.
Solved! used a CollectionView and added some buttons.
I created a new ViewController with a TableView and TableViewCell, and then a CollectionView with the CollectionViewCell. Inside that I added what I wanted. I created the array for the text and the the array for the images I was going to use. The the usual stuff regarding setting up each cell and each tableview (tableView and collectionView). For knowing which item the user tap I used the function didSelectItemAt and for the action I used a segue (because I wanted to send the user to another view).

UITableViewCell with StackView not dynamically sizing height

I have a custom UITableViewCell that contains a StackView with top, bottom, leading and trailing constraints to the content view of the cell.
When I set up my tableView, I give it an estimated height and also set the rowHeight to UITableViewAutomaticDimension.
In my cellForRowAt datasource method, I dequeue the cell and then call cell.setup() which adds any given number of views to my cell's stackView.
The problem is: My cell is always being sized to the estimated height of 80p. No matter how many views I add to the cell's stackView, it all crams into 80p height. The stackView, and thus the cell, isn't growing with each new item I insert into the cell before returning it in cellForRowAt datasource method.
I tried different distribution settings for my stackView, but I'm not sure what I'm doing wrong here.
Here is a simple demonstration of adding buttons to a stack view inside an auto-sizing table view cell:
class StackOfButtonsTableViewCell: UITableViewCell {
#IBOutlet var theStackView: UIStackView!
func setup(_ numButtons: Int) -> Void {
// cells are reused, so remove any previously created buttons
theStackView.arrangedSubviews.forEach { $0.removeFromSuperview() }
for i in 1...numButtons {
let b = UIButton(type: .system)
b.setTitle("Button \(i)", for: .normal)
b.backgroundColor = .blue
b.setTitleColor(.white, for: .normal)
theStackView.addArrangedSubview(b)
}
}
}
class ViewController: UITableViewController {
override func viewDidLoad() {
super.viewDidLoad()
tableView.rowHeight = UITableViewAutomaticDimension
tableView.estimatedRowHeight = 100
}
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 6
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "StackOfButtonsTableViewCell", for: indexPath) as! StackOfButtonsTableViewCell
cell.setup(indexPath.row + 1)
return cell
}
}
Assuming you have created a prototype cell, and its only content is a UIStackView configured as:
Axis: Vertical
Alignment: Fill
Distribution: Equal Spacing
Spacing: 8
and you have it constrained Top/Leading/Trailing/Bottom to the cell's content view, this is the result:
No need for any height calculations, and, since buttons do have intrinsic size, no need to set height constraints on the buttons.

spacing between UITableViewCells swift3

I am creating a IOS app in swift and want to add spacing between cells like this
I would like to give space of each table view cell same like my attach image.
How I can do that? and Right now all cells are coming without any space.
swift3
you can try this in your class of tableView cell:
class cell: UITableViewCell{
override var frame: CGRect {
get {
return super.frame
}
set (newFrame) {
var frame = newFrame
frame.origin.y += 4
frame.size.height -= 2 * 5
super.frame = frame
}
}
}
From Storyboard, your view hierarchy should be like this. View CellContent (as highlighted) will contain all the components.
Give margin to View CellContent of 10px from top, bottom, leading & trailing from its superview.
Now, select the tblCell and change the background color.
Now run your project, make sure delegate and datasource are properly binded.
OUTPUT
NOTE: I just added 1 UILabel in View CellContent for dummy purpose.
Update: UIEdgeInsetsInsetRect method is replaced now you can do it like this
contentView.frame = contentView.frame.inset(by: margins)
Swift 4 answer:
in your custom cell class add this function
override func layoutSubviews() {
super.layoutSubviews()
//set the values for top,left,bottom,right margins
let margins = UIEdgeInsets(top: 0, left: 0, bottom: 10, right: 0)
contentView.frame = UIEdgeInsetsInsetRect(contentView.frame, margins)
}
You can change values as per your need
***** Note *****
calling super function
super.layoutSubviews()
is very important otherwise you will get into strange issues
If you are using UITableViewCell to achieve this kind of layout, there is no provision to provide spacing between UITableViewCells.
Here are the options you can choose:
Create a custom UIView within UITableViewCell with clear background, so that it appears like the spacing between cells.
You need to set the background as clear of: cell, content view.
You can use UICollectionView instead of UITableView. It is much more flexible and you can design it the way you want.
Let me know if you want any more details regarding this.
One simple way is collection view instead of table view and give cell spacing to collection view and use
func collectionView(_ collectionView: UICollectionView,
layout collectionViewLayout: UICollectionViewLayout,
sizeForItemAtIndexPath indexPath: IndexPath) -> CGSize {
let widthSize = collectionView.frame.size.width / 1
return CGSize(width: widthSize-2, height: widthSize+20)
}
And if you want tableview only then add background view as container view and set background color white and cell background color clear color set backround view of cell leading, trilling, bottom to 10
backgroundView.layer.cornerRadius = 2.0
backgroundView.layer.masksToBounds = false
backgroundView.layer.shadowColor = UIColor.black.withAlphaComponent(0.2).cgColor
Please try it. It is working fine for me.
You can use section instead of row.
You return array count in numberOfSectionsInTableView method and set 1 in numberOfRowsInSection delegate method
Use [array objectAtIndex:indexPath.section] in cellForRowAtIndexPath method.
Set the heightForHeaderInSection as 40 or according to your requirement.
Thanks,Hope it will helps to you
- Statically Set UITableViewCell Spacing - Swift 4 - Not Fully Tested.
Set your tableView Row height to whatever value you prefer.
override func viewDidLoad() {
super.viewDidLoad()
tableView.estimatedRowHeight = <Your preferred cell size>
tableView.rowHeight = UITableViewAutomaticDimension
// make sure to set your TableView delegates
tableView.dataSource = self
tableView.delegate = self
}
extension YourClass : UITexFieldDelegate, UITextFieldDataSource {
//Now set your cells.
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell : UITableViewCell = tableView.dequeueReusableCell(withIdentifier: "yourCell", for: indexPath) as! UITableViewCell
//to help see the spacing.
cell.backgroundColor = .red
cell.textLabel?.text = "Cell"
return cell
}
//display 3 cells
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 3
}
//now lets insert a headerView to create the spacing we want. (This will also work for viewForHeaderInSection)
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
//you can create your own custom view here
let view = UIView()
view.frame = CGRect(x: 0, y: 0, width: tableView.frame.width, height: 44) //size of a standard tableViewCell
//this will hide the headerView and match the tableView's background color.
view.backgroundColor = UIColor.clear
return view
}
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 44
}
}

Prevent footer overlapping tableViewCell in UITableView - Swift

I have this table view which works how i want it to however i have a problem where the footer overlap the cells in the table view as seen in
How can i prevent this? This is my code for the footer
func tableView(tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
let footerView = UIView(frame: CGRectMake(0, 0, tableView.frame.size.width, 40))
// self.myTableView.tableFooterView = footerView;
let sectionString = Array(foodArray.keys)[section]
for value in caloriesArray[sectionString]! {
calories += value
}
totalCalories += calories
print(calories)
print(totalCalories)
let label = UILabel(frame: CGRectMake(footerView.frame.origin.x - 15, footerView.frame.origin.y, footerView.frame.size.width, 20))
label.textAlignment = NSTextAlignment.Right
label.text = "Total Calories: \(calories) "
footerView.addSubview(label)
calories = 0
return footerView
}
func tableView(tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
return 20.0
}
#IBAction func addFoodTapped(sender: AnyObject) {
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
let sectionString = Array(foodArray.keys)[indexPath.section]
foodArray[sectionString]?.removeAtIndex(indexPath.row)
caloriesArray[sectionString]?.removeAtIndex(indexPath.row)
print(foodArray)
viewDidAppear(true)
}
You can do that, Just make Style Grouped as shown below:
Just add some padding to the bottom of the content so that it doesn't overlap with the footer:
self.tableView.contentInset = UIEdgeInsetsMake(0, 0, FOOTER_HEIGHT, 0)
I know this is an old thread, so this is more so for others that encountered this (like myself).
The floating section footer is default behavior from my understanding. There are a couple of options that I can think of:
Provide your footer view with a background color (footerView.backgroundColor = UIColor.white) thus cleaning up the overlap.
or
Replace the section footer with a custom "Total Calories" cell that you add to the table after the last cell in that section, effectively acting like a footer cell.
Sorry for the delay. If you have modified the standard contentInsetAdjustmentBehavior of the tableView, you must adjust the tableView contentInset property to take into account the total height of the views at the bottom of the UITableView, like the tab bar. If contentInsetAdjustmentBehavior is set to "automatic" (or you didn't change the default value), then set the clipsToBounds property of your footer view to true so that its child views cannot be painted outside the footer view layer's frame. That should solve your issue.
Try to override this method
override func tableView(tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
return 44.0
}
Just set your label's background color to UIColor.white. and you are done !
label.backgroundColor = UIColor.white
Of course it overlaps. This is how footers and header work in UITableViews. You can set the footerView.backgroundColor to UIColor.gray, for example, to make it look better.

Resources