How can I add margin top to rows in tableView? Now I have:
Can I add space between rows?
My code is:
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! UITableViewCell
cell.imageView?.contentMode = .ScaleAspectFit
cell.imageView?.clipsToBounds = true
cell.imageView?.image = UIImage(data: data!)
cell.textLabel?.text = postTitle[indexPath.row]
cell.imageView?.layer.cornerRadius = 39
cell.imageView?.layer.masksToBounds = true;
return cell
}
I did try this line of code, but nothing:
cell.imageView.frame = CGRectOffset(cell.frame, 10, 10);
try this code for spacing between cells:
func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 10; // space b/w cells
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return postTitle.count // count of items
}
func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let header = UIView()
let imageName = "Divider.png"
let image = UIImage(named: imageName)
let imageView = UIImageView(image: image!)
imageView.frame = CGRect(x: 0, y: 0, width: self.view.bounds.size.width, height: 1)
header.addSubview(imageView)
header.backgroundColor = UIColor.clearColor()
return header
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 1
}
Here is divider image for you.
Related
I want that always the first visible cell in my UITableView has a different background color than the other cells.
Currently I have this for my UITableView
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 100
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableViewNew.dequeueReusableCell(withIdentifier: "cellNewPosts", for: indexPath) as! MainNewTableViewCell
return cell
}
And this, so the first cell is snapped to the top. So technically, I have the row which should be colored (currentItemOnTop):
scrollViewWillEndDragging(_ scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>) {
// Vibration Feedback
let generator = UIImpactFeedbackGenerator(style: .light)
generator.impactOccurred()
guard var scrollingToIP = tableViewNew.indexPathForRow(at: CGPoint(x: 0, y: targetContentOffset.pointee.y)) else {
return
}
var scrollingToRect = tableViewNew.rectForRow(at: scrollingToIP)
let roundingRow = Int(((targetContentOffset.pointee.y - scrollingToRect.origin.y) / scrollingToRect.size.height).rounded())
scrollingToIP.row += roundingRow
scrollingToRect = tableViewNew.rectForRow(at: scrollingToIP)
targetContentOffset.pointee.y = scrollingToRect.origin.y
currentItemOnTop = scrollingToIP.row
}
How can I achieve this? I tried a lot of stuff, but I think my problem is that I am using reusable cells.
Pretty easy, in cellForRow assign the color depending on currentItemOnTop
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableViewNew.dequeueReusableCell(withIdentifier: "cellNewPosts", for: indexPath) as! MainNewTableViewCell
if indexPath.row == currentItemOnTop {
cell.backgroundColor = .systemRed
} else {
cell.backgroundColor = // specify a default color
}
return cell
}
In scrollViewWillEndDragging reload the previous and current rows after updating the property
scrollViewWillEndDragging(_ scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>) {
// Vibration Feedback
let generator = UIImpactFeedbackGenerator(style: .light)
generator.impactOccurred()
guard var scrollingToIP = tableViewNew.indexPathForRow(at: CGPoint(x: 0, y: targetContentOffset.pointee.y)) else {
return
}
var scrollingToRect = tableViewNew.rectForRow(at: scrollingToIP)
let roundingRow = Int(((targetContentOffset.pointee.y - scrollingToRect.origin.y) / scrollingToRect.size.height).rounded())
scrollingToIP.row += roundingRow
scrollingToRect = tableViewNew.rectForRow(at: scrollingToIP)
targetContentOffset.pointee.y = scrollingToRect.origin.y
let previousRow = currentItemOnTop
currentItemOnTop = scrollingToIP.row
let indexPaths = [IndexPath(row: previousRow, section: 0), IndexPath(row: currentItemOnTop, section: 0)]
tableView.reloadRows(at: indexPaths, with: .none)
}
Have a nice day. I created a menu with Tableview, I want to add a logo and label to the top of this menu, just like in the android image. How can I make the menu visual like on Android? In the tableview I created, I show the name and icon of the menu. As with Android, I want to add a logo to the top of the menu.
class MyMenuTableViewController: UITableViewController {
let keychain = KeychainSwift()
private let menuOptionCellId = "Cell"
var selectedMenuItemLogin : Int = 0
var selectedMenuItem : Int = 0
let menuItem : [String] = ["Giriş"]
let menuIteminLogin : [String] = ["MENUITEM1" , "MENUITEM2" , "MENUITEM3","MENUITEM4"]
override func viewDidLoad() {
super.viewDidLoad()
tableView.contentInset = UIEdgeInsets(top: 64.0, left: 0, bottom: 0, right: 0)
tableView.separatorStyle = .singleLine
tableView.backgroundColor = UIColor(hex: 0x464646)
tableView.scrollsToTop = false
clearsSelectionOnViewWillAppear = false
let loginKeychain = keychain.get("LoginSuccess")
tableView.selectRow(at: IndexPath(row: selectedMenuItem, section: 0), animated: false, scrollPosition: .middle)
}
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return menuIteminLogin.count
}
var imageinLoginCell : [String] = ["gift.png" , "clock.png", "graphic.png","graphic.png"]
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
var cell = tableView.dequeueReusableCell(withIdentifier: menuOptionCellId)
if loginKeychain == "2" {
cell!.textLabel?.text = menuIteminLogin[indexPath.row]
cell!.imageView!.image = UIImage(named: imageinLoginCell[indexPath.row])
cell!.textLabel?.font = UIFont(name: "Helvetica-Bold", size: 18)
cell?.textLabel?.textAlignment = .right
if let myImage = UIImage(named: imageinLoginCell[indexPath.row]) {
let tintableImage = myImage.withRenderingMode(.alwaysTemplate)
cell!.imageView!.image = tintableImage
}
cell!.imageView!.tintColor = UIColor.white
if (indexPath.row == 2){
cell!.backgroundColor = UIColor(hex: 0xcf0700)
cell!.textLabel?.font = UIFont(name: "Helvetica-Bold", size: 19)
}
}
return cell!
}
override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 50.0
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let loginKeychain = keychain.get("LoginSuccess")
if loginKeychain == nil {
if (indexPath.row == selectedMenuItem) {
return
}
selectedMenuItem = indexPath.row
let mainStoryboard: UIStoryboard = UIStoryboard(name: "Main",bundle: nil)
var destViewController : UIViewController
switch (indexPath.row) {
case 0:
destViewController = mainStoryboard.instantiateViewController(withIdentifier: "LoginViewNew")
break
default: destViewController = mainStoryboard.instantiateViewController(withIdentifier: "LoginViewNew")
break
}
sideMenuController()?.setContentViewController(destViewController)
....
}
}
Use "tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView?"
and this function here for Height "tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat"
It will stick on top and the list will scroll underneath of it.
there is a table view and i create a button in Second cell . i handled Button Touch event with protocol .i want to add a empty text field in new row at current section Exactly below of phone number text field when add button touched but i cant handle it .
table view cell :
protocol InsertTableCellDelegate {
func insertTableCellDelegate_addrowbtn(sender:InsertTableCell1)
}
class InsertTableCell1: UITableViewCell {
var delegate : InsertTableCellDelegate?
#IBOutlet weak var tbCreateRow: UITableView!
#IBOutlet weak var txtPhoneNumber: JVFloatLabeledTextField!
override func awakeFromNib() {
super.awakeFromNib()
}
#IBAction func btn_Add_DidTouch(_ sender: Any) {
if let delegate = self.delegate
{
delegate.insertTableCellDelegate_addrowbtn(sender: self)
}
}
}
table view Delegates :
func numberOfSections(in tableView: UITableView) -> Int {
return 3
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 1
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if indexPath.section == 0 {
let cell0 = tableView.dequeueReusableCell(withIdentifier: "InsertTableCell0") as! InsertTableCell0
return cell0
}else if indexPath.section == 1 {
//this section should handle add textfield in new row when text button touhed
let cell1 = tableView.dequeueReusableCell(withIdentifier: "InsertTableCell1") as! InsertTableCell1
cell1.delegate = self
return cell1
}else {
let cell2 = tableView.dequeueReusableCell(withIdentifier: "InsertTableCell2") as! InsertTableCell2
cell2.txtEmail.text = strEditEmail
return cell2
}
}
//protocol of button :
func insertTableCellDelegate_addrowbtn(sender: InsertTableCell1) {
print("touched")
}
numberOfRowsInSection have fixed number of cell. First you need to create a
dynamic dataSource.
sample code :
var dataSource : [Int] = Array.init(repeating: 1, count: 3)
func numberOfSections(in tableView: UITableView) -> Int {
return dataSource.count
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return dataSource[section]
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if indexPath.section == 0 {
let cell0 = tableView.dequeueReusableCell(withIdentifier: "InsertTableCell0") as! InsertTableCell0
return cell0
}else if indexPath.section == 1 {
//this section should handle add textfield in new row when text button touhed
let cell1 = tableView.dequeueReusableCell(withIdentifier: "InsertTableCell1") as! InsertTableCell1
cell1.delegate = self
return cell1
}else {
let cell2 = tableView.dequeueReusableCell(withIdentifier: "InsertTableCell2") as! InsertTableCell2
cell2.txtEmail.text = strEditEmail
return cell2
}
}
//protocol of button :
func insertTableCellDelegate_addrowbtn(sender: InsertTableCell1) {
dataSource[1] = dataSource[1] + 1
tableView.reloadData() // or you can use beginUpdates() and endUpdates()
}
Sample of code for add new Row when click on add button in Section
//Create outlet for table view
#IBOutlet weak var currentInsetTableView: UITableView!
//Declare these variable
let reuseInsetCellIdentifier = "insertCell";
let titleSection = ["Add Phone", "Add Email"]
var arrayForCellInSection = Array<Any>()
//Add this code in viewDidLoad()
currentInsetTableView.delegate = self
currentInsetTableView.dataSource = self
currentInsetTableView.estimatedRowHeight = 200
currentInsetTableView.rowHeight = UITableView.automaticDimension
currentInsetTableView.register(UINib(nibName: "CurrentInsertTableViewCell", bundle: nil), forCellReuseIdentifier: reuseInsetCellIdentifier)
arrayForCellInSection = Array.init(repeating: 1, count: titleSection.count)
//Implematation of UITablewView Delegate
func numberOfSections(in tableView: UITableView) -> Int {
return titleSection.count
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return arrayForCellInSection[section] as! Int
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: reuseInsetCellIdentifier, for: indexPath)
as! CurrentInsertTableViewCell
cell.backgroundColor = UIColor.black
return cell
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 50
}
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let headerView = UIView.init(frame: CGRect.init(x: 0, y: 0, width: tableView.frame.width, height: 50))
headerView.backgroundColor = UIColor.black
let buttonX = 10
let buttonY = 10
let buttonWidth = 30
let buttonHeight = 30
let button = UIButton(type: .system)
let imgAdd = UIImage(named: "Add")
button.setImage(imgAdd, for: .normal)
button.addTarget(self, action: #selector(buttonClickedForInsertRowInSection(sender:)), for: .touchUpInside)
button.frame = CGRect(x: buttonX, y: buttonY, width: buttonWidth, height: buttonHeight)
button.tag = section
headerView.addSubview(button)
let label = UILabel()
label.frame = CGRect.init(x: button.frame.size.width + CGFloat((2 * buttonX)), y: CGFloat(buttonY), width: headerView.frame.width - button.frame.size.width + CGFloat((3 * buttonX)), height: headerView.frame.height - CGFloat((2 * buttonY)))
label.text = titleSection[section]
label.textColor = UIColor.white
headerView.addSubview(label)
return headerView
}
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 50
}
//CurrentInsertTableViewCell Desing
//Final Result: When we press two times on first section add button & one times on second section add button
I want to create a footer which is dynamic to the height of the tableview cells.
My initial situation looks like:
If I click on a row, it change the height of this cell to 194 (44 before)
It don't show all rows.
If I get the footer -150 it looks like:
And if I close all cells it looks like and the 150 which I get to footer with -150 are white here:
My code:
var selectedCellIndexPath: Int?
let selectedCellHeight: CGFloat = 194.0
let unselectedCellHeight: CGFloat = 44.0
var cellsHeight = [44, 44, 44]
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.beginUpdates()
if selectedCellIndexPath != nil && selectedCellIndexPath == indexPath.row {
selectedCellIndexPath = nil
}
else {
selectedCellIndexPath = indexPath.row
}
if selectedCellIndexPath != nil {
tableView.scrollToRow(at: indexPath, at: .none, animated: true)
}
tableView.endUpdates()
}
func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
let rowHeight:CGFloat = 44
var rowsHeight:CGFloat = 3 * rowHeight
/*for i in 0..<cellsHeight.count {
rowsHeight += CGFloat(cellsHeight[i])
}*/
let topHeight = UIApplication.shared.statusBarFrame.height + self.navigationController!.navigationBar.frame.height
let viewHeight = self.view.frame.height
let headerHeight:CGFloat = 30
let height = viewHeight - topHeight - rowsHeight - headerHeight //- 150
return CGFloat(height)
}
Only one row will have the height 194 and the other 44. Any ideas how to solve the problem?
Thx
Edit:
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 3
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let dateFormatter = DateFormatter()
//dateFormatter.dateStyle = DateFormatter.Style.short
dateFormatter.dateFormat = "dd.MM.yyyy HH:mm"
if indexPath.row == 0 {
let cell = tableView.dequeueReusableCell(withIdentifier: "workoutDateCell", for: indexPath) as! WorkoutDateTableViewCell
cell.typeLabel.text = "Beginn"
cell.dateDatepicker.date = Date()
cell.dateDatepicker.tag = indexPath.row
cell.dateLabel.text = dateFormatter.string(from: cell.dateDatepicker.date)
cell.selectionStyle = .none
return cell
}
else if indexPath.row == 1 {
let cell = tableView.dequeueReusableCell(withIdentifier: "workoutDateCell", for: indexPath) as! WorkoutDateTableViewCell
cell.typeLabel.text = "Ende"
cell.dateDatepicker.date = Date()
cell.dateDatepicker.tag = indexPath.row
cell.dateLabel.text = dateFormatter.string(from: cell.dateDatepicker.date)
cell.selectionStyle = .none
return cell
}
else {
let cell = tableView.dequeueReusableCell(withIdentifier: "workoutSportsCell", for: indexPath) as! WorkoutSportsTableViewCell
cell.sportsLabel.text = "Sportart"
cell.sportstypeLabel.text = workoutSports[coreData.getSportsIndex()]
cell.sportsPicker.delegate = self
cell.sportsPicker.dataSource = self
cell.sportsPicker.selectRow(coreData.getSportsIndex(), inComponent: 0, animated: false)
cell.selectionStyle = .none
return cell
}
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
if selectedCellIndexPath == indexPath.row {
return selectedCellHeight
}
return unselectedCellHeight
}
To archive this you can use only cells instead of footer view.
Step 1: Remove Footer View.
Step 2: Add Cell of Date Picker.
Step 3: When you click on Begin & End DateTime cell, then insert DateTime cell below selected cell and reload table view.
Step 4: Hope that will resolve your problem.
Let me know if you have any query.
Edit: As per discuss you only need to remove the extra cell separator by using tableFooterViewForSection.
So you only need to add below line to solve your problem:
tableView.tableFooterView = UIView(frame: CGRect(x:0, y:0, width:tableView.frame.width, heigth:0))
And Remove func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat method.
Hope it will help you.
i have this code for my tableview in tvOS project in swift 3, i want color cell when scroll it not focus! please can yon explain how do it?
this my code
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return tvChannelsArray.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
// Show TV Channels names
cell.textLabel?.text = ((tvChannelsArray[(indexPath as NSIndexPath).row] as AnyObject).object(forKey: "channel") as! String)
cell.imageView?.image = UIImage(named: "\(cell.textLabel!.text!)")
return cell
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
channelsTableView.isHidden = false;
return 100
}
In your tableview delegate implement the UISsrollViewDelegate method ScrollViewDidScroll
func scrollViewDidScroll(_ scrollView: UIScrollView) {
for cell in tableView.visibleCells {
if let currentCellPath = tableView.indexPath(for: cell),
let selectedCellPath = tableView.indexPathForSelectedRow {
guard currentCellPath != selectedCellPath else {
continue
}
}
let red = Float(cell.frame.origin.y / scrollView.contentSize.height)
cell.contentView.backgroundColor = UIColor(colorLiteralRed: red, green: 0.5, blue: 0.25, alpha: 1)
}
}