Always keep cell on the top of uitableview - ios

I have an application that is viewbased and I am adding a uitableview as a subview to the main view. The uitableview is full with class Category cells. Everything works fine, but I want to have “Quick notes” Category always on the top of the uitableview. This means when I reloadData() in the Array, “Quick Notes” is always with index 0 and it goes on the bottom of the uitableview. And when I create new cell I need it to go under the “Quick Notes” section.
Please help me, what code I need to achieve that functionality and where I need to put it. Thanks!
Edit:
Thats where I am adding "Quick Notes" to the Realm database.
private let categories = try! Realm()
private init() {
if categories.objects(Category.self).isEmpty {
createCategoryWith(title: "Quick Notes", color: "#FF0000", icon: "quickNotes")
}
}
Update the array in the ViewController:
func didCreateCategory(category: Category) {
RealmHandler.shared.createCategoryWith(title: category.title, color: category.color, icon: category.icon)
self.categories = RealmHandler.shared.getAllCategories()
tableView.reloadData()
}
DataSourceDelegate:
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "categoryCell", for: indexPath)
cell.textLabel?.text = categories[categories.count - (1+indexPath.row)].getTitle()
cell.contentView.backgroundColor = hexStringToUIColor(hex: categories[categories.count-(1+indexPath.row)].getColor())
return cell
}

use viewForHeaderInSection delegate method of tableView.
tableView(_ tableView: UITableView, viewForHeaderInSection section: Int)
here you can define your header cell.
then implement your logic that what do you want to show on this cell.
this headerCell will be always on top of your tableView.

Related

How do I delete UITableview cells by tapping a UIButton?

I want to delete all the UITableviewCells in my Tableview by tapping a button
UITableView DataSource Methods
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return UserList.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "FriendAddCell" , for: indexPath) as! AddFriendLTableViewCell
cell.lb_Email.text = UserList[indexPath.row].userEmail
let imageUrl = URL(string: UserList[indexPath.row].imageUrl)
cell.img_Avatar.loadImageUrl(url: imageUrl!)
return cell
}
My Button Function
#IBAction func btn_NewAddUser(_ sender: Any) {
UserList.removeAll()
table_SearchFirends.reloadData()
}
the cells I tried to delete still exist when I add a new cell
How can I delete all the cells by pressing the button?
How can I make the tableView as if there were no rows created?
How I can understand your problem that you see empty lines with separator lines on bottom.
Make this for remove extra lines:
tableView.tableFooterView = UIView()
And some advise - use camelCase style in Swift.

Is there a way to display a UI Cell a single time and another UI Cell multiple times?

I have a UITableView which represent a questionnaire with Dynamic UI Cells. I've created 2 cells.
The first UI Cell need to be all the time on the top (like a Title/Header) and the second UI Cell need to be Dynamic (this means that the second UI Cell can display 10 or 20 questions). Is there any way to do this ?
I've already created a UITableViewCell for both UI Cells and I linked all the components.
Now I don't know where to specify that Cell 0 to be returned 1 time and Cell 1 to be returned X times.
Also how I keep Cell 0 on the top all the time ?
Here is a printscreen which reflect my issue:
Here is my code:
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
switch indexPath.row {
// Static cell - Checks Left
case 0:
let cell = tableView.dequeueReusableCell(withIdentifier: "checksLeftCell", for: indexPath) as! ChecksLeftTableViewCell
return cell
// Dynamic cell - Questions
case 1:
let cell = tableView.dequeueReusableCell(withIdentifier: Constants.defectAndDamageCell, for: indexPath) as! DefectAndDamageCheckCell
cell.configCell()
cell.delegate = self
return cell
default:
return UITableViewCell()
}
}
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
switch indexPath.row {
case 0: return 100
case 1: return 400
default:
return 170
}
}
I expect to have "frozen" cell on the top and the second one to be a dynamic cell.
Thanks if you read this and I hope that I explained well what is in my mind.
This isn't sign of good thinking about design. It looks like you don't need UITableView at all. You can achieve better result using basic UIViews for each component such as Title, question details, tags, etc.
You can help yourself using UIStackView.
Instead of a static cell you can use a Section Header with a custom View inside of it:
func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let nameLabel = UILabel(frame: CGRect(x: 10, y: 0, width: tabelView.frame.width, height: 40))
nameLabel.text = //
nameLabel.font = taskNameLabel.font.withSize(14)
//Or add whatever you need here
let sub = UIView(frame: CGRect(x: 0, y: 0, width: tabelView.frame.size.width, height: 40))
sub.backgroundColor = .white
sub.addSubview(NameLabel)
return sub
}
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: Constants.defectAndDamageCell, for: indexPath) as! DefectAndDamageCheckCell
cell.configCell()
cell.delegate = self
return cell
}
I would try using UICollectionView instead of the tableview.
From UICollectionView, use the UICollectionViewDelegateFlowLayout delegate.
func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView { #your code for header view }
https://developer.apple.com/documentation/uikit/uicollectionviewdatasource/1618037-collectionview
or
Create a section header in your TableView, and create a custom view in it.
So your TableView would have 1 section header and 1 row.
Good luck.
There are many ways to solve this.
If you want a static view that sticks to the top try this:
Subclass a UIViewController and add a container UIView at the top/leading/trailing. Embed your header labels and content in the content view. Next, add a UITableView and pin it to the leading/trailing/bottom of the superview. Make your view controller the data source and delegate.
In this way, you will still have scrolling within the tableview and can reload the cells as needed while managing your static header content as IBOutlets.
If you use the selected answer with stack views, you will have to implement a scrolling solution by embedding your stack view in a UIScrollView when your content is longer than the screen size. You should probably just stick to using a tableview because that behavior is inherited.

Swift 3.0 Using a Table View to Show and Add Comments

I am interested in having a tableview for comments (something similar to instagram comments). So far, I have used a custom cell to set up a textView for comments in my set array, dataName. I was wondering how I could go about setting up a textfield and button on the last row of the tableview that would act as the place to input more comments. Do I need to create another customcell for this and implement this in cellForRowAt indexPath ?
var comments = ["I like this item","Where did you get this?", "I can't believe you found this!", "Hello", "Yay"]
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return comments.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! CustomCell
cell.commentView.text = dataName[indexPath.row]
cell.commentView.textColor = UIColor.lightGray
cell.commentView.isEditable = false
cell.commentView.isScrollEnabled = false
return cell
}
You can accomplish you desired effect by adding a view that contains a text field and a button as the footer view of the tableview. And when a new comment is added you will proceed to add the comment to the array, and reload the tableview or insertRow with animation.
You already have one cell prototype called "Cell". Just add another cell prototype called "Comment". Now you have two cell prototypes with two different identifiers. If you're on the last row, ask for the "Comment" cell prototype in your dequeue call.

UITableViewCells invisible

Requirement :
I have a list of UITableviewCell loaded from a nib that I'm presenting on UITableview. The first time I open the UIViewController all cells are shown correctly and work as expected.
Issue :
If I navigate back to the parent and then open the UIViewController again the UITableviewCell are 'invisible'. I say invisible because with a breakpoint in cellForRowAt I can see that the table view does load all cells and the cells are valid.
Code :
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 13
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 40
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = (project?.sliderData.sliders[indexPath.row].view)! as UITableViewCell
print(cell.contentView.subviews.count)
if let left = cell.viewWithTag(2) as? UILabel {
left.text = "left"
}
if let middle = cell.viewWithTag(3) as? UILabel {
middle.text = "middle"
}
if let right = cell.viewWithTag(4) as? UILabel {
right.text = "right"
}
return cell
}
Screen Shot Image
Expected observation :
I was thinking that maybe the subviews of the cells get released because I don't have any bindings to them in IB. To test this I'm printing the count of subviews and writing some text to the subview labels. And everything seems to go fine, the cells are loaded and the labels are there but the cells just don't show up.
But then, if I scroll the TableView up and down a little to get some cells updated those cells do appear at the top and bottom of the view as shown in the pic.
You need to call dequeueReusableCell(withIdentifier: "cell") inside your code then will show your table cell. It will reuse cell for your all numbers of row data content.
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell") as! UITableViewCell
return cell
}
More Details : How to create uitableview with multiple sections in iOS Swift.
Did not find reason why the tableView behaves the way it does so I solved the issue by dequeueing default cells. The views provided by the slider objects are added as subviews to the dequeued cells. Now the subviews can of course be any UIViews.
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
var cell = tableView.dequeueReusableCell(withIdentifier: "sliderCell")
if cell == nil {
cell = UITableViewCell.init(style: .default, reuseIdentifier: "sliderCell")
}
cell?.addSubview((project?.sliderData.sliders[indexPath.row].view)!)
return cell!
}

iOS - UITableView add single static cell to dynamic table

I Have a UITableView which is controlled by NSFetchedResultsController. I want to add single cell to the first row and make this cell static. In other words, there will be a button which will open another View Controller.
Until now, I was ok with fetched results controller and table. Now I'm a bit confused. How should I do this?
Instead using a header might be ok too, but I don't want this header to be on top all the time. I want this cell to be just like WhatsApp iOS "Create new group" cell on chats panel.
Thank you!
var dataArray = ["A","B","C"]
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.dataArray.count+1
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
{
if indexPath.row == 0
{
let cell = tableView.dequeueReusableCell(withIdentifier: "CreateNewGroupCell") as! CreateNewGroupCell
return cell
}
else
{
// Get the data from Array
let data = self.dataArray[indexPath.row-1]
// Logic to show other cells
let cell = tableView.dequeueReusableCell(withIdentifier: "OtherCell") as! OtherCell
return cell
// ....
}
}
You will need to create tableview with number of rows fetched from NSFetchedResultsController +1. Also in cellForRowIndex method you will need to add a check like indexPath.row == 0 and in there you will make the changes.
Also you will have to add action for that button within that section. You can also set different custom tableview for first row.
It can be similar to following:
func tableView(_ tableView: UITableView, cellForRowAtIndexPath indexPath: IndexPath) -> UITableViewCell {
if(indexPath.row==0){
let cell = tableView.dequeueReusableCell(withIdentifier: "CellWithButton", for: indexPath) as! CellWithButton
}
else{
let cell = tableView.dequeueReusableCell(withIdentifier: "OtherCells", for: indexPath) as! OtherCells
//here add data for cells from your array
}
return cell
}

Resources