Cell width too big for tableview width - ios

I have a programmatic tableview nested in a caraousel, but when it displays, the programmatic cell is always set wider than the tableview its in. If I print the carousel item width, tableview width and cell width I get: 281, 281, 320(iphone5 screen width). I tried adding constraints to the cell but keep getting nil errors, I believe because the cell hasn't been made yet. So I'm not sure where to put the constraints so that I stop getting these errors, I only need the cell content view width to match the tableview width, but how do I get the tableview width in my custom cell which has been made programmatically? Heres my current code without any constraints:
TableView:
import UIKit
class SplitterCarouselItemTableView: UITableView {
var splitter: BillSplitter?
required init(frame: CGRect, style: UITableViewStyle, splitter: BillSplitter) {
super.init(frame: frame, style: style)
self.splitter = splitter
setupView()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func setupView() {
if Platform.isPhone {
let tableViewBackground = UIImageView(image: UIImage(data: splitter?.image as! Data, scale:1.0))
self.backgroundView = tableViewBackground
tableViewBackground.contentMode = .scaleAspectFit
tableViewBackground.frame = self.frame
}
self.backgroundColor = .clear
self.separatorStyle = .none
}
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
tableView.register(SplitterCarouselItemTableViewCell.classForCoder(), forCellReuseIdentifier: "splitterCarouselItemTableViewCell")
let cell: SplitterCarouselItemTableViewCell = tableView.dequeueReusableCell(withIdentifier: "splitterCarouselItemTableViewCell") as! SplitterCarouselItemTableViewCell
var item = ((allBillSplitters[tableView.tag].items)?.allObjects as! [Item])[indexPath.row]
if allBillSplitters[tableView.tag].isMainBillSplitter {
getMainBillSplitterItems(splitter: allBillSplitters[tableView.tag])
item = mainBillSplitterItems[indexPath.row]
}
let count = item.billSplitters?.count
if count! > 1 {
cell.name!.text = "\(item.name!)\nsplit \(count!) ways"
cell.price!.text = "£\(Double(item.price)/Double(count!))"
} else {
cell.name!.text = item.name!
cell.price!.text = "£\(item.price)"
}
return cell
}
Cell:
import UIKit
class SplitterCarouselItemTableViewCell: UITableViewCell {
var name: UILabel!
var price: UILabel!
var view: UIView!
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:)")
}
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: "splitterCarouselItemTableViewCell")
self.backgroundColor = .clear
let width = Int(contentView.bounds.width)
let height = Int(contentView.bounds.height)
view = UIView(frame: CGRect(x: 0, y: 2, width: width, height: height - 4 ))
view.backgroundColor = UIColor.white.withAlphaComponent(0.5)
let viewHeight = Int(view.bounds.height)
let viewWidth = Int(view.bounds.width)
price = UILabel(frame: CGRect(x: viewWidth - 80, y: 0, width: 75, height: viewHeight))
price.font = UIFont.systemFont(ofSize: 15.0)
price.textAlignment = .right
name = UILabel(frame: CGRect(x: 5, y: 0, width: width, height: viewHeight))
name.font = UIFont.systemFont(ofSize: 15.0)
name.numberOfLines = 0
view.addSubview(name)
view.addSubview(price)
contentView.addSubview(view)
}
}
I understand the init shouldn't be filled with all that code and will be extracted later. Its just there until i resolve the width issue.
Thanks for any help.

The challenge is that the tableView.dequeueReusableCell(withIdentifier:) method indirectly calls init(frame:) on your UITableViewCell class. There are a couple of ways to solve this:
Override init(frame:) in SplitterCarouselItemTableViewCell and set your width there when you call super.init(frame:)
Modify your cell.frame in your func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) method
Using Autolayout is problematic with UITableView cells. You don't want to go messing with all the subviews there.

Try adding this
cell.frame = CGRect(x: CGFloat(Int(cell.frame.minX)),
y: CGFloat(Int(cell.frame.minY)),
width: tableView.frame.width,
height: cell.frame.height)
to your
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
This fixed the problem for me.
My UITableViewController and UITableViewCell were done programmatically

in viewDidLoad Grab your tableView Outlet or your tableView Instance if you made it programmatically, then access to rowHeight and give an Value to it : Like This code Below:
enter code here
private let MenuTableView:UITableView = {
let tableView = UITableView(frame: .zero, style: .grouped)
tableView.register(FoodTableViewCell.self, forCellReuseIdentifier: FoodTableViewCell.identifier)
tableView.showsVerticalScrollIndicator = false
return tableView
}()
override func viewDidLoad() {
super.viewDidLoad()
view.addSubview(MenuTableView)
MenuTableView.rowHeight = 50
}

Related

UITableViewCell behaves differently in iOS 11

I have done a UITableViewCell programmatically and it worked just fine with iOS 10. But after updating with iOS 11 and XCode 9, it behaves differently. The layout looks scrambled as below.
But if I tap on the cell then it rearranges and looks fine as below.
Here the code for UITableViewCell
import UIKit
import SnapKit
class AboutCell: UITableViewCell {
let roleLabel : UILabel = {
var tablelabel = UILabel()
tablelabel.font = UIFont (name: "Avenir Next Medium", size: 22)
tablelabel.textAlignment = .center
tablelabel.clipsToBounds = true
tablelabel.translatesAutoresizingMaskIntoConstraints = false
return tablelabel
}()
let nameLabel : UILabel = {
let tablelabel = UILabel()
tablelabel.font = UIFont (name: "Avenir Next Medium", size: 16)
tablelabel.textAlignment = .center
tablelabel.clipsToBounds = true
tablelabel.translatesAutoresizingMaskIntoConstraints = false
return tablelabel
}()
let webUrlLabel : UILabel = {
let tablelabel = UILabel()
tablelabel.font = UIFont (name: "Avenir Next Medium", size: 16)
tablelabel.textAlignment = .center
tablelabel.clipsToBounds = true
tablelabel.translatesAutoresizingMaskIntoConstraints = false
return tablelabel
}()
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
setupViews()
}
override func layoutSubviews() {
super.layoutSubviews()
roleLabel.frame = CGRect(x: 0, y: 10, width: self.contentView.bounds.size.width-20, height: 25)
nameLabel.frame = CGRect(x: 0, y: roleLabel.frame.origin.y+25, width: self.bounds.size.width-20, height: 25)
webUrlLabel.frame = CGRect(x: 0, y: nameLabel.frame.origin.y+25, width: self.bounds.size.width-20, height: 25)
}
func setupViews(){
contentView.addSubview(roleLabel)
contentView.addSubview(nameLabel)
contentView.addSubview(webUrlLabel)
}
func setValuesForCell(contributor : Contributors){
roleLabel.text = contributor.contributorRole
nameLabel.text = contributor.contributorName
webUrlLabel.text = contributor.contributorWeb
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
}
and the extension I wrote for TableView delegate and datasource
extension AboutController : UITableViewDelegate, UITableViewDataSource{
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return contributorList.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell : AboutCell = tableView.dequeueReusableCell(withIdentifier: self.cellid, for: indexPath) as! AboutCell
cell.selectionStyle = .default
let contributor : Contributors = contributorList[indexPath.row]
cell.setValuesForCell(contributor: contributor)
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
print(indexPath.row)
tableView.deselectRow(at: indexPath, animated: true)
}
}
and the ViewDidLoad method
override func viewDidLoad() {
super.viewDidLoad()
tableView.estimatedRowHeight = 100.0
tableView.rowHeight = 100
tableView.register(AboutCell.self, forCellReuseIdentifier: self.cellid)
view.addSubview(tableView)
tableView.snp.makeConstraints { (make) in
make.top.right.bottom.left.equalToSuperview()
}
let mayu = Contributors(contibutorRole: "Developer", contributorName: "J Mayooresan", contributorWeb: "http://jaymayu.com")
let janie = Contributors(contibutorRole: "Voice Artist", contributorName: "M Jananie", contributorWeb: "http://jaymayu.com")
let arjun = Contributors(contibutorRole: "Aathichudi Content", contributorName: "Arjunkumar", contributorWeb: "http://laymansite.com")
let artist = Contributors(contibutorRole: "Auvaiyar Art", contributorName: "Alvin", contributorWeb: "https://www.fiverr.com/alvincadiz18")
contributorList = [mayu, arjun, janie, artist]
tableView.delegate = self
tableView.dataSource = self
self.tableView.reloadData()
}
Since you're laying out your tableView using autolayout, you also need to ensure translatesAutoresizingMaskIntoConstraints is set to false.
SnapKit should be setting the tableView's translatesAutoresizingMaskIntoConstraints to false for you already.
Since you're laying out the cells manually (using frames in layoutSubviews). Setting the cells subview's translatesAutoresizingMaskIntoConstraints to false is likely not needed.
See Apple Docs here for translatesAutoresizingMaskIntoConstraints

Why does my custom UITableViewCell return the wrong width when calling self.frame.width?

This has been answered in a comment by #Kevin. I wasn't calling layoutSubviews.
Everything is created programmatically. Nothing is done via storyboards. Here is a stripped down version of the tableView code:
func configure(cell: UITableViewCell, for indexPath: IndexPath) {
guard let cell = cell as? HistoryTableViewCell else {
return
}
// I set up the cells various properties here.
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: historyCellIdentifier, for: indexPath) as! HistoryTableViewCell
configure(cell: cell, for: indexPath)
return cell
}
Here is a stripped down version of my UITableViewCell:
class HistoryTableViewCell: UITableViewCell {
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:)")
}
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
self.backgroundColor = UIColor.blue
let test = UIView(frame: CGRect(x: 0, y: 0, width: self.frame.width, height: 10))
test.backgroundColor = UIColor.black
self.addSubview(test)
}
override func prepareForReuse() {
super.prepareForReuse()
}
}
Notice I set the test views width to self.frame.width. Which produces this:
Printing self.frame.width in the HistoryTableViewCell results in 320 which is the width of an iPhone 5s. Any idea why? I'm assuming it's something like I am creating the cell before something so it defaults to the smallest size.
Another odd thing is if I try and set the test views center.x to self.center.x it stays where it is which I think is weird as the background colour shows the cell is the width of the screen.
Thanks
Unless you don't want to use autolayout or autoresizingmaske, have UI components as property and update their frame in the layoutSubview.
class HistoryTableViewCell: UITableViewCell {
let test = UIView()
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:)")
}
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
self.backgroundColor = UIColor.blue
self.test.backgroundColor = UIColor.black
self.contentView.addSubview(test)
}
override func prepareForReuse() {
super.prepareForReuse()
}
}
override func layoutSubviews() {
super.layoutSubviews()
test.frame = CGRect(x: 0, y: 0, width: self.frame.width, height: 10)
}

UITableViewCell Not Displaying Data - Swift Playgrounds

I have been trying to implement some custom cells in a table view I created in a view controller in the swift playgrounds iPad app. Please note that I have seen a lot of the other stack overflow posts dealing with similar issues but have not been able to find a solution that fixes my problem.
Here is my CustomCell Class:
class CustomCell: UITableViewCell {
let projectImage = UIImageView()
//let projectDivider = UIView()
let projectTitle = UILabel()
override func awakeFromNib() {
projectImage.frame = CGRect(x: 0, y: 0, width: 100, height: 100)
//projectDivider.frame = CGRect(x: 100, y: 0, width: 20, height: 100)
projectTitle.frame = CGRect(x: 120, y: 0, width: 200, height: 100)
self.contentView.addSubview(projectImage)
//self.contentView.addSubview(projectDivider)
self.contentView.addSubview(projectTitle)
}
}
The following is my view controller code:
class AboutViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
let tableView = UITableView()
let cellReuseIdentifier: String = "cell"
var projectTitles = ["Madhubani Coffee", "World Savvy", "Zipshare", "CrashThatCode", "Future Plans"]
var images: [UIImage] = [UIImage(named: "IMG_0061.JPG")!, UIImage(named: "IMG_0064.JPG")!, UIImage(named: "IMG_0062.JPG")!, UIImage(named: "IMG_0062.JPG")!, UIImage(named: "IMG_0062.JPG")!]
override func viewDidLoad() {
view.backgroundColor = UIColor.white
tableView.frame = CGRect(x: -82.5, y: 250, width: 600, height: 600)
tableView.delegate = self
tableView.dataSource = self
tableView.backgroundColor = UIColor.white
self.tableView.register(CustomCell.self as AnyClass, forCellReuseIdentifier: cellReuseIdentifier)
view.addSubview(tableView)
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 5
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
var cell = self.tableView.dequeueReusableCell(withIdentifier: cellReuseIdentifier, for: indexPath) as! CustomCell
if cell == nil {
cell = UITableViewCell(style: UITableViewCellStyle.default, reuseIdentifier: cellReuseIdentifier) as! CustomCell
}
cell.projectImage.image = images[indexPath.row]
cell.projectTitle.text = projectTitles[indexPath.row]
cell.clipsToBounds = true
return cell
}
}
I don't know what the problem is. It seems that the cells simply do not display. Any help would be appreciated!
Your problem is that you don't have a nib (or xib) file to do an awakeFromNib from.
Try doing this for your CustomCell instead:
class CustomCell: UITableViewCell {
let projectImage = UIImageView()
//let projectDivider = UIView()
var projectTitle = UILabel()
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
projectImage.frame = CGRect(x: 0, y: 0, width: 100, height: 30)
//projectDivider.frame = CGRect(x: 100, y: 0, width: 20, height: 100)
projectTitle.frame = CGRect(x: 10, y: 0, width: 200, height: 30)
projectTitle.font = UIFont.systemFont(ofSize: 20.0)
//self.contentView.addSubview(projectImage)
//self.contentView.addSubview(projectDivider)
self.contentView.addSubview(projectTitle)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}

Swift - UITableView displaying weird white cell

I making a tableView of different item. The item have a name, and a picture.
Here is what I get :
And I want :
1 - to delete the white space which appears at the beginning and the end of the table view
2 - for the separator to be all the width
Here is my code :
CustomTableView
// Controls
var interestsCategory:[InterestCategory];
// Load components when the view is loaded
override func viewDidLoad() {
super.viewDidLoad();
//Hide Nav bar
self.navigationController?.navigationBarHidden = true;
// Table View
self.tableView = UITableView(frame: CGRect(x: 0, y: 3.2 * self.view.frame.height / 13, width: self.view.frame.width ,height: 8.8 * self.view.frame.height / 13), style: .Grouped)
//self.tableView.style = UITableViewStyle.Grouped;
self.tableView.registerClass(ProximityInterestCategoryCell.self, forCellReuseIdentifier: "ProximityInterestCategoryCell");
self.tableView.tableFooterView = UIView(frame: CGRectZero)
self.tableView.tableHeaderView = UIView(frame: CGRectZero)
//self.view.addSubview(tableView);
}
init()
{
self.interestsCategory = [];
self.interestsCategory.append(InterestCategory(name:"FINANCE", image: UIImage(named: "business2.png")!));
self.interestsCategory.append(InterestCategory(name:"SPORTS", image: UIImage(named: "sports2.png")!));
self.interestsCategory.append(InterestCategory(name:"WEB",image: UIImage(named: "web2.png")!));
self.interestsCategory.append(InterestCategory(name:"TOURISM",image: UIImage(named: "tourism2.png")!));
self.interestsCategory.append(InterestCategory(name:"ENERGY",image: UIImage(named: "energy2.png")!));
self.interestsCategory.append(InterestCategory(name:"TECHNOLOGY",image: UIImage(named: "technology2.png")!));
self.interestsCategory.append(InterestCategory(name:"MUSIC",image: UIImage(named: "music2.png")!));
self.interestsCategory.append(InterestCategory(name:"CHEMICAL",image: UIImage(named: "chemical2.png")!));
self.interestsCategory.append(InterestCategory(name:"INSURANCE",image: UIImage(named: "insurance2.png")!));
self.interestsCategory.append(InterestCategory(name:"HEALTH",image: UIImage(named: "health2.png")!));
self.interestsCategory.append(InterestCategory(name:"FASHION",image: UIImage(named: "fashion2.png")!));
self.interestsCategory.append(InterestCategory(name:"REAL ESTATE",image: UIImage(named: "realestate2.png")!));
print(" number : \(self.interestsCategory.count)");
super.init(nibName: nil, bundle: nil);
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
print("numberOfRowsInSection");
return self.interestsCategory.count;
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
print("cellForRowAtIndexPath : \(indexPath.row)");
print(self.interestsCategory[indexPath.row].name);
let cellIdentifier = "ProximityInterestCategoryCell";
let cell = self.tableView.dequeueReusableCellWithIdentifier( cellIdentifier, forIndexPath: indexPath) as! ProximityInterestCategoryCell;
cell.nameLabel.text = self.interestsCategory[indexPath.row].name;
cell.nameLabel.sizeToFit();
cell.background.image = self.interestsCategory[indexPath.row].image;
cell.background.clipsToBounds = true;
return cell;
}
// Override to support conditional editing of the table view.
override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return false if you do not want the specified item to be editable.
return true
}
/*
override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
print("heightForRowAtIndexPath");
return 120;
}*/
CustomCell
var background: UIImageView!
var nameLabel: UILabel!
var checkButton: UIButton!
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
backgroundColor = UIColor.clearColor();
selectionStyle = .None;
self.background = UIImageView(frame: CGRect(x: 0, y: 0, width: self.frame.width, height:self.frame.height));
self.background.alpha = 1;
self.background.contentMode = UIViewContentMode.ScaleAspectFill;
self.background.clipsToBounds = true;
contentView.addSubview(background);
self.nameLabel = UILabel(frame: CGRect(x: 50, y: 0, width: self.frame.width-50, height:self.frame.height));
self.nameLabel.center.y = self.center.y;
self.nameLabel.textColor = UIColor.whiteColor();
self.nameLabel.backgroundColor = UIColor.clearColor();
contentView.addSubview(nameLabel);
self.checkButton = UIButton(frame: CGRect(x: 6 * self.frame.width/7.4, y: 0, width: 0.7 * self.frame.width/7.4, height: 0.8 * self.frame.height/13));
self.checkButton.center.y = self.center.y;
self.checkButton.setImage(UIImage(named: "RondNonCoche.png"), forState: UIControlState.Normal);
self.checkButton.setImage(UIImage(named: "RondCoche.png"), forState: UIControlState.Selected);
self.checkButton.clipsToBounds = true;
contentView.addSubview(checkButton);
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func prepareForReuse() {
super.prepareForReuse()
}
override func layoutSubviews() {
super.layoutSubviews();
}
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
If someone could help me, that would be great :)
Issue1
Please set
self.tableView.delegate = self
self.tableView.dataSource = self
Issue 2 separator inset
-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
// Remove seperator inset
if ([cell respondsToSelector:#selector(setSeparatorInset:)]) {
[cell setSeparatorInset:UIEdgeInsetsZero];
}
// Prevent the cell from inheriting the Table View's margin settings
if ([cell respondsToSelector:#selector(setPreservesSuperviewLayoutMargins:)]) {
[cell setPreservesSuperviewLayoutMargins:NO];
}
// Explictly set your cell's layout margins
if ([cell respondsToSelector:#selector(setLayoutMargins:)]) {
[cell setLayoutMargins:UIEdgeInsetsZero];
}
}
These space came from this line :
self.tableView = UITableView(frame: CGRect(x: 0, y: 3.2 * self.view.frame.height / 13, width: self.view.frame.width ,height: 8.8 * self.view.frame.height / 13), style: .Grouped)
It should be
self.tableView = UITableView(frame: CGRect(x: 0, y: 3.2 * self.view.frame.height / 13, width: self.view.frame.width ,height: 8.8 * self.view.frame.height / 13), style: .Plain)
style: .Plain doesn't add space where style: .Grouped does.

Swift: UIView appear in UITableView cell

Im having an issue putting a UIView that I created in a specific UITableView cell. Here is my code:
class ViewController: UIViewController,UITableViewDelegate,UITableViewDataSource {
//MARK : Properties
var tableView = UITableView()
var items: [String] = ["Age", "Gender", "Smoking Hx", "Occup. -Ag", "Family Hx", "Chronic Lung Disease Radiology", "Chronic Lung Disease Hx", "Nodule Border", "Nodule Location", "Satellite Lesions", "Nodule Pattern Cavity", "Nodule Size"]
var navigationBar = NavigationBar()
var gender = GenderView()
var maleIcon = MaleIconView()
override func viewDidLoad() {
super.viewDidLoad()
//Create TableView
tableView.frame = CGRectMake(0, self.view.bounds.height * 0.097, self.view.bounds.width,
self.view.bounds.height - self.view.bounds.height * 0.097);
tableView.delegate = self
tableView.dataSource = self
tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: "cell")
self.view.addSubview(tableView)
//Create Navigation Bar with custom class
self.navigationBar = NavigationBar(frame: CGRect(x: 0, y: 0, width: self.view.bounds.width, height: self.view.bounds.height * 0.097))
self.view.addSubview(navigationBar)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.items.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell:UITableViewCell = tableView.dequeueReusableCellWithIdentifier("cell")! as UITableViewCell
cell.textLabel?.text = self.items[indexPath.row]
//Cell wont turn grey when selected
cell.selectionStyle = UITableViewCellSelectionStyle.None
//Want to add UIView male Icon in first row
if(indexPath.row == 0){
maleIcon = MaleIconView(frame: CGRect(x: 0, y: 0, width: 55, height: 55))
maleIcon.center.x = cell.center.x + cell.center.x * 0.5
maleIcon.center.y = cell.contentView.center.y
maleIcon.layer.cornerRadius = 0.5 * maleIcon.bounds.size.width
//maleIcon.layer.borderWidth = 3.0
cell.addSubview(maleIcon)
}
return cell
}
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return self.view.bounds.height * 0.15
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
print("You selected cell #\(indexPath.row)!")
}
}
Maybe the issue exists within the MaleIconView()? Here is the code to that:
class MaleIconView: UIView {
var maleView = UIView()
override init(frame: CGRect) {
super.init(frame: frame)
self.frame = frame
setUpView()
}
func setUpView(){
maleView.frame = CGRectMake(0, 0, self.bounds.width, self.bounds.height)
maleView.alpha = 1
maleView.backgroundColor = UIColor.blackColor()
maleView.layer.cornerRadius = 0.5 * maleView.bounds.size.width
self.addSubview(maleView)
}
func hide(){
self.removeFromSuperview()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
Im trying to get the UIView to appear on the right side of the cell 0. There is also this issue where the indexPath's are all off, i think this could be of some issue to why the UIView appears in multiple cells. Thank you in advance!
Here is the code for what should help you with your issues. I made a few assumptions about how you may be trying to implement. But this should be a great start for you.
https://www.dropbox.com/sh/2ilyfnc1pqurjfd/AAC2rU-zlvUtjdKYV33JrQJQa?dl=0
I also highly recommend that you use auto layout for your various view dimensions rather than hard coding weird offsets. It may be difficult to start with. But it definitely pays off in the long run!
It's kinda strange that maleIcon is UIViewController property in your code.
Did you try to put in cellForRowAtIndexPath?
like that:
//Want to add UIView male Icon in first row
if(indexPath.row == 0){
let maleIcon = MaleIconView(frame: CGRect(x: 0, y: 0, width: 55, height: 55))
I'm not sure it will help with reusable cells though. What will help (but there is slightly more work) is to create your own cell class, add maleIcon as property, register this class with your table and put this in your cellForRowAtIndexPath like that:
if (indexPath.row == 0) {
cell.maleIcon.hidden = false}
else {
cell.maleIcon.hidden = true}

Resources