UITableViewCell from Xib, cell hight and cell selection area - ios

I have a UITableViewController, which has a custom cell that I want to display an image and labels. screenshots can explain my problem very well, it looks like this
.
And when I select any cell it looks like
In tableviewcontroller cell is not visible in proper shape according to constraints
here is my custom cell with autolayout constraints
How I can fix this issue? ... I created this tableviewcontroller programmatically without using storyboard.
here is code sample of data source and delegates of tableviewcontroller
override func numberOfSections(in tableView: UITableView) -> Int {
var numOfSections: Int = 0
let count = conversations.count
if count > 0 {
// tableView.separatorStyle = .none
numOfSections = 1
tableView.backgroundView = nil
}
else
{
let frame = CGRect(x: 0,
y: 0,
width: tableView.bounds.size.width,
height: tableView.bounds.size.height)
let noDataLabel: UILabel = UILabel(frame: frame)
noDataLabel.text = "You don't have any messages. 🙃"
noDataLabel.textColor = UIColor.black
noDataLabel.textAlignment = .center
tableView.backgroundView = noDataLabel
tableView.separatorStyle = .none
}
return numOfSections
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return conversations.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "inboxCell", for: indexPath) as! InboxCell
cell.conversation = conversations[indexPath.row]
return cell
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let uids = conversations[indexPath.row].conversationUseruids
for uid in uids{
if uid == Account.account.user.uid{
}
else{
User.getUser(with: uid, completion: { (user) in
self.selectedUser.append(user!)
})
}
}
tableView.deselectRow(at: indexPath, animated: true)
let index = indexPath.row as Int
messageVC.conversationIndex = index
messageVC.conversation = self.conversations[index]
navigationController?.pushViewController(messageVC, animated: true)
}
override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 80
}

it happen because your image not have upper lower constraint if not working than let me know

Related

Background colours changing automatically in Multiple Cell Selection Swift

I have a table view. I am using multiple cell selection. Everything is working correctly, functionality wise, but UI wise it is not. Whenever I select a cell and scroll down I see the color is changed in another cell below though that cell was never actually selected. What I have done is this for the cell:
class FollowSportsCell: UITableViewCell {
#IBOutlet weak var sportL: UILabel!
#IBOutlet weak var backImg: UIImageView!
override func awakeFromNib() {
super.awakeFromNib()
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
}
override func prepareForReuse() {
super.prepareForReuse()
backImg.backgroundColor = UIColor(hexString: "E6E6E6")
sportL.textColor = .black
}
And, here are delegates.
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return sportsArr!.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: cellReuseIdentifier, for: indexPath) as! FollowSportsCell
let sport = sportsArr![indexPath.row]["id"] as! Int
cell.sportL.text = sportsArr![indexPath.row]["title"] as? String
cell.selectionStyle = UITableViewCell.SelectionStyle.none
if selectedSports.contains(sport) {
cell.sportL.textColor = .white
cell.backImg.backgroundColor = UIColor(hexString: "4293CC")
}
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
selectedCell += 1
let sport = sportsArr![indexPath.row]["id"]
selectedSports.append(sport! as! Int)
if selectedCell > 1
{
collectionB[0].backgroundColor = UIColor(hexString: "4293CC")
collectionB[0].isEnabled = true
}
}
func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {
selectedCell -= 1
selectedSports = selectedSports.filter{$0 != sportsArr![indexPath.row]["id"] as! Int}
if selectedCell < 2
{
collectionB[0].backgroundColor = .lightGray
collectionB[0].isEnabled = false
}
}
When, the number is low like 4 or 5 and the scroll doesn't appear everything is good, but once they are like 20-22 then, I get this issue. Any help?
You should handle background color in tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) .
Check and use below code. Hope it will work
var selectedCells = Array<NSInteger>()
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return sportsArr!.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: cellReuseIdentifier, for: indexPath) as! FollowSportsCell
cell.sportL.text = sportsArr![indexPath.row]["title"] as? String
cell.selectionStyle = UITableViewCell.SelectionStyle.none
if self.selectedCells.contains(indexPath.row) {
cell.sportL.textColor = .white
cell.backImg.backgroundColor = UIColor(hexString: "4293CC")
if self.selectedCells.count > 1
{
collectionB[0].backgroundColor = UIColor(hexString: "4293CC")
collectionB[0].isEnabled = true
}
}
else
{
//Here Set your default color for cell backImgr background color
cell.sportL.textColor = // set default color
cell.backImg.backgroundColor = // set default color
}
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let cell = tableView.cellForRow(at: indexPath) as! FollowSportsCell
if self.selectedCells.contains(indexPath.row) {
//Here you will get selected cell and going to deselect...Do anything with deselection
if let index = self.selectedCells.index{$0 == indexPath.row}
{
self.selectedCells.remove(at: index)
}
cell.sportL.textColor = .black
cell.backImg.backgroundColor = UIColor(hexString: "E6E6E6")
selectedCell -= 1
selectedSports = selectedSports.filter{$0 != sportsArr![indexPath.row]["id"] as! Int}
if self.selectedCells.count < 2
{
collectionB[0].backgroundColor = .lightGray
collectionB[0].isEnabled = false
}
}
else
{
self.selectedCells.append(indexPath.row)
print(cell.sportL.text!)
selectedCell += 1
let sport = sportsArr![indexPath.row]["id"]
selectedSports.append(sport! as! Int)
}
self.yourtblView.reloadData()
}
Please select your default and selected color in "CellForRowAtIndexPAth". Please check the below code.
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: cellReuseIdentifier, for: indexPath) as! FollowSportsCell
cell.sportL.text = sportsArr![indexPath.row]["title"] as? String
cell.selectionStyle = UITableViewCell.SelectionStyle.none
let sport = sportsArr![indexPath.row]["id"]
cell.sportL.textColor = default cell colour
cell.backImg.backgroundColor = default cell colour
if selectedSports.contain(sport) {
cell.sportL.textColor = required cell colour
cell.backImg.backgroundColor = required cell colour
}
return cell
}
import UIKit
class TableVC: UIViewController,UITableViewDelegate,UITableViewDataSource {
#IBOutlet weak var tableView : UITableView!
var arrayOfTitle : [titleOfArray] = [titleOfArray]()
override func viewDidLoad() {
super.viewDidLoad()
if self.tableView != nil {
self.tableView.delegate = self
self.tableView.dataSource = self
}
for i in 0...20 {
self.arrayOfTitle.append(titleOfArray(title: "Test\(i)", isSelectedIndex: false))
}
// Do any additional setup after loading the view.
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 80
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.arrayOfTitle.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = self.tableView.dequeueReusableCell(withIdentifier: "cell")
cell?.textLabel!.text = self.arrayOfTitle[indexPath.row].title
cell?.textLabel!.textColor = self.arrayOfTitle[indexPath.row].isSelectedIndex ? UIColor.red : UIColor.blue
return cell!
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
for i in 0...self.arrayOfTitle.count-1 {
self.arrayOfTitle[i].isSelectedIndex = false
}
self.arrayOfTitle[indexPath.row].isSelectedIndex = true
tableView.reloadData()
}
}
class titleOfArray : NSObject {
var title : String!
var isSelectedIndex : Bool!
init(title:String! ,isSelectedIndex :Bool) {
self.title = title
self.isSelectedIndex = isSelectedIndex
}
}
this might be helpful

UITableviewCell text disappears after a blink on every reload

Reload is not calling cellForRowAt whenever I am trying to reload without the main thread closure. This is my code:
class UtititySwitcher:NSObject, UITableViewDataSource, UITableViewDelegate {
let utilityTableview = UITableView()
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 3
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = UITableViewCell(style: .default, reuseIdentifier: "Mycell")
cell.textLabel?.text = "hello"
return cell
}
func Open(loginID:String, view:UIView)
{
let frm = view.bounds
let backView = UIView(frame: frm)
self.utilityTableview.frame = CGRect(x: frm.minX + 10, y: frm.midY - 50, width: frm.width - 20, height: 100)
self.utilityTableview.backgroundColor = UIColor.white
self.utilityTableview.delegate = self
self.utilityTableview.dataSource = self
backView.addSubview(self.utilityTableview)
view.addSubview(backView)
OperationQueue.main.addOperation {
self.utilityTableview.reloadData()
}
}
}
You haven't set the delegate and data source for the utilityTableview so this table view is not informed who shall it listen to and take data from. At the class init, add utilityTableview.delegate = self and utilityTableview.dataSource = self
I think the reason is :
the OperationQueue have not init
you can try:
let operationQueue = OperationQueue()
operationQueue.main.addOperation {
self.utilityTableview.reloadData
}

ios 11 UITableViewHeaderFooterView not properly scroll in animation

I have collapse and expand animation in UITableView. Tableview has two section in which first section data is collapse and expand. This thing perfectly working with ios 10 but in ios 11 Section view repeated or overlapped with cell data which is expanded.
Below is my code
//MARK: -Table View delegate Method
func numberOfSections(in tableView: UITableView) -> Int {
return read_Localizable("titleHelpSection").components(separatedBy: ",").count
}
//MARK: -Table View Datasource Method
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return UITableViewAutomaticDimension
}
func tableView(_ tableView: UITableView, estimatedHeightForHeaderInSection section: Int) -> CGFloat{
return 44.0
}
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
var headerView = tableView.dequeueReusableHeaderFooterView(withIdentifier: "headerView")
let arrSection = read_Localizable("titleHelpSection").components(separatedBy: ",")
if headerView == nil
{
headerView = UITableViewHeaderFooterView(reuseIdentifier: "headerView")
headerView?.contentView.backgroundColor = UIColor.white
let lblResult = UILabel()
lblResult.tag = 123456
lblResult.font = AppCommonSNMediumFont()
lblResult.textColor = UIColor.black
lblResult.translatesAutoresizingMaskIntoConstraints = false
headerView?.contentView.addSubview(lblResult)
let seperator = UIView()
seperator.translatesAutoresizingMaskIntoConstraints = false
seperator.backgroundColor = UIColor.black
headerView?.contentView.addSubview(seperator)
headerView?.contentView.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|[seperator]|", options: [], metrics: nil, views: ["seperator":seperator]))
headerView?.contentView.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|-[lable]-(>=8)-|", options: [], metrics: nil, views: ["lable":lblResult]))
headerView?.contentView.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|-[lable]-[seperator(1)]|", options: [], metrics: nil, views: ["lable":lblResult,"seperator":seperator]))
}
if let lblResult = headerView?.contentView.viewWithTag(123456) as? UILabel
{
lblResult.text = arrSection[section]
}
return headerView
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return UITableViewAutomaticDimension
}
func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat {
return 20.0
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if section == 0
{
return (arrHelpData.count)
}
else
{
return 1
}
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if indexPath.section == 0
{
var cell = tableView.dequeueReusableCell(withIdentifier: "HelpCell") as? CellHelp;
if cell == nil {
cell = CellHelp(style: .default, reuseIdentifier: "HelpCell")
cell?.selectionStyle = .none
cell?.txtContain.delegate = self
}
if let objModel = arrHelpData.object(at: indexPath.row) as? HelpModel
{
cell?.lblTitle.text = objModel.helpTitle
if objModel.isExpanded == true
{
cell?.txtContain.text = objModel.helpDesc
}
else
{
cell?.txtContain.text = ""
}
cell?.imgArrow.isHighlighted = !objModel.isExpanded
}
return cell!
}
else
{
var cell = tableView.dequeueReusableCell(withIdentifier: "DefultCell")
if cell == nil
{
cell = UITableViewCell(style: .default, reuseIdentifier: "DefultCell")
cell?.textLabel?.textColor = color1F87A3()
cell?.textLabel?.font = AppCommonSNRegularFont()
cell?.selectionStyle = .none
cell?.textLabel?.numberOfLines = 0
}
cell?.textLabel?.text = read_Localizable("titleSettings")
return cell!
}
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if indexPath.section == 0 && indexPath.row < (arrHelpData.count)
{
if let objModel = arrHelpData.object(at: indexPath.row) as? HelpModel
{
if objModel.isExpanded == true
{
objModel.isExpanded = false
}
else
{
objModel.isExpanded = true
}
tableView.reloadData()
}
}
}
Actual view
Section overlapped on cell data
This is very frustrating iOS11 issue, something to do around estimatedHeight issue, If you really want to keep the self sized row and header then u need to go with the below approach.
Declare variable which holds the height of the cell/header and store height into that and used it as below:
var cellHeightDictionary: NSMutableDictionary // To overcome the issue of iOS11.2
override func viewDidLoad() {
super.viewDidLoad()
tableView.rowHeight = UITableViewAutomaticDimension
tableView.estimatedRowHeight = 125
}
override func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
cellHeightDictionary.setObject(cell.frame.size.height, forKey: indexPath as NSCopying)
}
func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat {
if cellHeightDictionary.object(forKey: indexPath) != nil {
let height = cellHeightDictionary.object(forKey: indexPath) as! CGFloat
return height
}
return UITableViewAutomaticDimension
}
This is the only solution which worked for me for iOS11 issues with auto sizing cells. Otherwise people suggest to keep estimatedHeight 0 to get rid off such issues.
In your case first try doing this for cell and that doesn't solve the issue completely then do same for header height also. Hope this helps!
Don't forget to test in both iOS11.1 and iOS11.2.

Avoid Data repetition in UITableView cells when scrolling

I need an auto scrolling Image slider in top of viewcontroller followed by list of some entities(dynamic cells with image and title). To implement that I have taken a uitableview and I'm adding scrollview to my first cell, and my code is as follows
public func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
if indexPath.row == 0{
return 200
}
else {
return 50
}
}
public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 20
}
public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
if indexPath.row == 0 {
let sv = UIScrollView(frame: CGRect(x: 0, y: 0, width: cell.frame.width, height: cell.frame.height))
sv.auk.show(url: "url for image1")
sv.auk.show(url: "url for image2")
cell.addSubview(sv)
print("inside if")
}
else {
print("else")
cell.textLabel?.text = "cool"
}
return cell
}
I'm using this repository to create image slider which creates slider on a scrollview, So for first cell I have added scrollview. But as you can see in the picture the image slider reappears on multiple rows. Please tell me what is the mistake that I'm doing.In case if there is any better approaches please suggest .
Try taking a separate class for dynamic cells. Dequeue both the cells (static and dynamic cells) in the cellForRow method as follows:
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return indexPath.row == 0 ? 200 : 50
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 20 }
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if indexPath.row == 0 {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
scrollViewWidth = cell.frame.width
scrollViewHeight = cell.frame.height
let scrollView = prepareScrollView(width: scrollViewWidth, height: scrollViewHeight)
cell.addSubview(scrollView )
print("First row")
return cell
}
else {
let myCustomCell: MyCustomTableViewCellClass = tableView.dequeueReusableCell(withIdentifier: "MyCustomTableViewCellIdentieier", for: indexPath) as! MyCustomTableViewCellClass
myCustomCell.textLabel?.text = "Cool"
print("Other dynamic rows")
return myCustomCell
}
}
func prepareScrollView(_ width: Float, height: Float) -> UIScrollView {
let scrollViewFrame = CGRect(x: 0, y: 0, width: width, height: height)
let scrollView = UIScrollView(frame: scrollViewFrame)
scrollView.auk.show(url: "url for image1")
scrollView.auk.show(url: "url for image2")
return scrollView
}
Take a separate class as MyCustomTableViewCellClass of type UITableViewCell and subclass your dynamic cell with this class. Don't forget to give cell identifier as "MyCustomTableViewCellIdentieier"
After this, your static cell will dequeue only once and no chances od repeating UI elements
You can try this code in your table view cell class -
override func prepareForReuse() {
//set your lable and image view to nil
}
SideMenuTVCell is a my custom UITableViewCell class -
Hope like this you have your own class within this class you add prepareForReuse() method -
class SideMenuTVCell: UITableViewCell {
#IBOutlet weak var iconIView: UIImageView!
#IBOutlet weak var lblTitle: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
}
override func setHighlighted(_ highlighted: Bool, animated: Bool) {
super.setHighlighted(highlighted, animated: animated)
}
override func prepareForReuse() {
//set your lable and image view to nil
self.iconIView.image = nil
self.lblTitle.text = nil
}
}

Setting TableViewCell Label colour on row selection Swift 3

I have a TableView, and the table is populated from an array. The cell is of type TableViewCell.xib. I want to change the colour of the label in the cell.
Here's my TableViewController
struct cell_data {
let label1: String!
}
class TableViewController: UITableViewController {
let cellDataArray = [cell_data]([cell_data(label1: "This text is for label 1")])
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return cellDataArray.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = Bundle.main.loadNibNamed("TableViewCell", owner: self, options: nil)?.first as! TableViewCell
cell.label_1.text = cellDataArray[indexPath.row].label1
cell.selectionStyle = .none
let whiteRoundedView : UIView = UIView(frame: CGRect(x:10, y:5, width: self.view.frame.size.width - 20, height: cell.frame.size.height - 7))
whiteRoundedView.layer.backgroundColor = UIColor.green.cgColor
whiteRoundedView.layer.masksToBounds = false
whiteRoundedView.layer.shadowOffset = CGSize(width: -1, height: 1)
whiteRoundedView.layer.shadowOpacity = 0.3
cell.contentView.addSubview(whiteRoundedView)
cell.contentView.sendSubview(toBack: whiteRoundedView)
return cell
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let cell = tableView.cellForRow(at: indexPath)
}
override func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {
let cell = tableView.cellForRow(at: indexPath)
}
}
What I want to do be able to do is change the colour of the label of the cell when I select a row without affecting the UIView inside the cell. That is, once I change the height of the UIView when I select a row, I have tried reloading but reloading the cell set the UIView's height to the original setting.
And once I have set the label's colour, I want to set it back to it's original colour when I deselect the row.
I hope I made it clear enough. Thanks in advance.
You don't need to reloading the cell to update the label's color. You can try by overriding method in your TableViewCell with the following code:
override func setSelected(selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
if (selected) {
//Change your label color for selected state
} else {
//Change your label color for unselected state
}
}
try this:
func tableView(tableView: UITableView, didHighlightRowAtIndexPath indexPath: NSIndexPath)
{
let cell = tableView.cellForRowAtIndexPath(indexPath)! as! customTableViewCell // name of your custom cell class
cell.label_1.backgroundColor = UIColor.whiteColor()//give your selection color
}
Try this
override func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {
let cell = tableView.cellForRow(at: indexPath) as yourCell
cell.yourlable.textcolor = yourColor;
}

Resources