Table Cells not loading on scroll - ios

I am creating a messaging page in my app and I am having some serious trouble. When the page first loads it looks fine but when you start to scroll down everything gets all messed up. New cells do not load and then when I scroll back up most cells are gone except for normally 1 that shows up and it is in the wrong place.
There is some Async action going on. When the message is sent it sends to the server and then when it returns I reload the data and scroll to that newly entered message at the bottom. This is very buggy as well. Most of the time when sending the message the new cell does not show up. Then after sending 1 or 2 more then will all show up.
Here is my ViewController that is also my Data source and Delegate
import UIKit
class MessageDetailController: UIViewController,UITableViewDataSource,UITableViewDelegate, UITextFieldDelegate {
#IBOutlet weak var lblMessageText: UITextField!
#IBOutlet weak var sendViewHeightConstraint: NSLayoutConstraint!
#IBOutlet weak var messagesTable: UITableView!
#IBOutlet weak var sendMsgView: UIView!
#IBOutlet weak var sendMessageView: UIView!
var messageDetailArray = [Message]()
override func viewDidLoad() {
super.viewDidLoad()
self.lblMessageText.delegate = self
self.view.bringSubviewToFront(self.sendMessageView)
self.messagesTable.separatorStyle = UITableViewCellSeparatorStyle.None
self.messagesTable.dataSource = self
self.messagesTable.delegate = self
self.messagesTable.reloadData()
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return messageDetailArray.count
}
func textFieldShouldReturn(textField: UITextField) -> Bool {
_ = MessageService().sendMessage("James", message: lblMessageText.text!, callback: loadMessages)
lblMessageText.text = ""
return true
}
func loadMessages(jsonData:NSArray){
dispatch_async(dispatch_get_main_queue(),{
var messages = [Message]()
for messageTest in jsonData {
if let message = messageTest as? NSDictionary {
messages.append(Message(messageType:Message.QA.A, from:message["user_display_label"] as! String, messageText:message["message"] as! String, timeSent:NSDate()))
}
}
self.messageDetailArray = messages;
self.messagesTable.reloadData()
self.messagesTable.scrollToRowAtIndexPath(NSIndexPath(forRow: self.messageDetailArray.count - 1, inSection: 0), atScrollPosition: UITableViewScrollPosition.Bottom, animated: true)
})
}
#IBAction func endedEditing(sender: AnyObject) {
self.view.layoutIfNeeded()
UIView.animateWithDuration(0.2, animations: {
self.sendViewHeightConstraint.constant = 40
self.view.layoutIfNeeded()
}, completion: nil)
}
#IBAction func startedEditing(sender: AnyObject) {
self.view.layoutIfNeeded()
UIView.animateWithDuration(0.2, animations: {
self.sendViewHeightConstraint.constant = 295
self.view.layoutIfNeeded()
}, completion: nil)
}
#IBAction func sendMessage(sender: AnyObject) {
_ = MessageService().sendMessage("James", message: lblMessageText.text!, callback: loadMessages)
lblMessageText.text = ""
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let thisMsg = messageDetailArray[indexPath.row]
let cell: MessageDetailATableViewCell = tableView.dequeueReusableCellWithIdentifier("messageCenterA", forIndexPath: indexPath) as! MessageDetailATableViewCell
cell.msgLabel?.text = thisMsg.messageText;
cell.msgLabel.sizeToFit()
cell.msgLabel.numberOfLines = 0
cell.frame = CGRectMake(0,
0,
self.view.bounds.width,
cell.frame.size.height);
let myInsets = UIEdgeInsetsMake(7, 8, 7, 8)
let bubbleImage = UIImage(named: "balloon_read_right")?.resizableImageWithCapInsets(myInsets)
let bubbleImageView = UIImageView(image: bubbleImage)
bubbleImageView.frame = CGRectMake(0, 0, cell.bubbleView.bounds.width, cell.bubbleView.bounds.height)
cell.bubbleView.addSubview(bubbleImageView)
cell.bubbleView.bringSubviewToFront(cell.msgLabel)
return cell
}
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
let messageSize:CGSize = PTSMessagingCell.messageSize(messageDetailArray[indexPath.row].messageText)
return messageSize.height + 2 * PTSMessagingCell.textMarginVertical() + 40
}
}
If you read through that you will notice that I use this class so I will include it for you. It is just the tablecell and does not do much.
import UIKit
class MessageDetailATableViewCell: UITableViewCell {
#IBOutlet weak var bubbleView: UIView!
#IBOutlet weak var msgImageView: UIImageView!
#IBOutlet weak var msgLabel: UILabel!
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
}
}
I have messed around with this code a lot trying to get it to work and I cont find anyone else who has the same bug. Any help would be greatly appreciated!
Thanks!!

The problem is caused by the fact that you set the frame of your cells. You set the origin of all cells to (0,0). That destroys the layout of the table view. You should never touch the frames of the cells from the outside.
If you want to set the height of your cells you have to do that in the UITableViewDelegate method tableView(_:heightForRowAtIndexPath:). Calculate the cell height there and return it.
You do not have to set the width of your cells, because in a UITableView the UITableViewCells always have the same width as the UITableView.

Related

Cannot trigger didSelectRowAt in UITableViewDelegate

I'm trying to get the selected row in a table in Swift 4. The code presented for completeness, is as follows:
import UIKit
import WebKit
class FactorDetailsViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
#IBOutlet weak var goalTitle: UILabel!
#IBOutlet weak var goalCopy: UITextView!
#IBOutlet weak var goalBenefit: UILabel!
#IBOutlet weak var goalName: UILabel!
#IBOutlet weak var graph: SimpleChart!
#IBOutlet weak var measurement: UILabel!
#IBOutlet weak var measurementRange: UILabel!
#IBOutlet weak var updated: UILabel!
#IBOutlet weak var factorCopy: UITextView!
#IBOutlet weak var impact: UILabel!
#IBOutlet weak var actionsTable: UITableView!
#IBOutlet weak var researchTable: UITableView!
#IBOutlet weak var scrollView: UIScrollView!
#IBOutlet weak var stackView: UIStackView!
var factorData : Factor?
var currentCategory : FactorCategory?
var recommendedActions : [Action] = []
var relatedResearch : [Research] = []
var goal : Goal?
var reading:Double?
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
self.title = factorData?.factorName
measurement.text = String(reading!)
self.actionsTable.delegate = self
self.actionsTable.dataSource = self
self.actionsTable.isEditing = false
self.researchTable.delegate = self
self.researchTable.dataSource = self
self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Update", style: .done, target: self, action: #selector(addStuff))
goalCopy.text = goal?.copy
goalBenefit.text = "BIG BENEFIT"
goalTitle.text = goal?.title
for cat in (factorData?.categories)! {
let s = SimpleChartData(min : Double(cat.min), max : Double(cat.max), label : cat.label, label2 : String(cat.max))
if( graph.canLoad ) {
graph.data!.append(s)
}
}
graph.reading = reading!
// Pin the edges of the stack view to the edges of the scroll view that contains it
stackView.leadingAnchor.constraint(equalTo: scrollView.leadingAnchor).isActive = true
stackView.trailingAnchor.constraint(equalTo: scrollView.trailingAnchor).isActive = true
stackView.bottomAnchor.constraint(equalTo: scrollView.bottomAnchor).isActive = true
stackView.widthAnchor.constraint(equalTo: scrollView.widthAnchor).isActive = true
}
#objc func addStuff() {
// how does this work? Just takes you to the quiz again
let storyboard = UIStoryboard(name: "12Factor", bundle: nil)
let vc = storyboard.instantiateViewController(withIdentifier: "AllQuestionViewController") as UIViewController
present(vc, animated: true, completion: nil)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func configure( factor : Factor )
{
factorData = factor
let mirrored_object = Mirror(reflecting: HRResponses.shared)
reading = 1.0
for (_, attr) in mirrored_object.children.enumerated() {
if let property_name = attr.label as String? {
if factorData?.responseField == property_name {
if let a = attr.value as? String, let aDouble = Double(a) {
reading = aDouble
}
}
}
}
currentCategory = factor.categories.first( where: {$0.min < reading! && $0.max > reading! })
for aind in (currentCategory?.actions)! {
let act = SignalModel.model.actions.first( where: {$0.id == aind})
recommendedActions.append(act!)
}
for rind in (currentCategory?.research)! {
let act = SignalModel.model.research.first( where: {$0.id == rind})
relatedResearch.append(act!)
}
goal = SignalModel.model.goals.first( where: {$0.id == currentCategory?.goals[0]})
}
func tableView(_ tableView: UITableView,
willSelectRowAt indexPath: IndexPath) -> IndexPath? {
print("works?")
return nil
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath)
{
if tableView == self.actionsTable {
let vc : ActionViewController = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "ActionViewController") as! ActionViewController
navigationController?.pushViewController(vc, animated: true)
}
if tableView == self.researchTable {
}
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// Return the number of items in the sample data structure.
var count:Int?
if tableView == self.actionsTable {
count = currentCategory?.actions.count
}
if tableView == self.researchTable {
count = currentCategory?.research.count
}
return count!
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
var cell:UITableViewCell?
if tableView == self.actionsTable {
cell = tableView.dequeueReusableCell(withIdentifier: "ActionCell", for: indexPath as IndexPath)
let action = recommendedActions[indexPath.row]
(cell as! ActionCell).configure(a:action)
}
if tableView == self.researchTable {
cell = tableView.dequeueReusableCell(withIdentifier: "ResearchCell", for: indexPath as IndexPath)
let research = relatedResearch[indexPath.row]
(cell as! ResearchCell).configure(r:research)
}
return cell!
}
}
Now, that's too much code. The relevant parts are here:
self.actionsTable.delegate = self // yes, this is the delegate
self.actionsTable.dataSource = self
self.actionsTable.isEditing = false // no, we're not editing
As I understand it, this should be enough to have selections in the actionsTable trigger the
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath)
method. However, nothing happens. The other UITableViewDelegate methods are called, so this controller is the delegate for this table, however this one method is not ever triggered. Reading through the Apple documentation here I see that the method isn’t called when the table view is in editing mode (that is, the isEditing property of the table view is set to true), but my table isn't in editing mode. Is there something else that could be going wrong with my table that wouldn't allow it to send an event to a UITableViewDelegate? I suspect that this has something to do with the table being inside a UIScrollView, which I've read isn't best practice, but with the design I've been given, is non-negotiable sadly.
Your problem is not the delegate, all of that code is good. Your problem is that the parent scroll view is consuming the taps, not the table view. Remember, UITableView is a direct subclass of UIScrollView so placing a table view inside a scroll view is no different than placing a scroll view within a scroll view. UITableView has all of the default scroll view delegates built into it so just use those.
You should not embed UIWebView or UITableView objects in UIScrollView
objects. If you do so, unexpected behavior can result because touch
events for the two objects can be mixed up and wrongly handled.
Apple dox
I know it's not the answer you wanted because this wasn't your doing but I personally would not proceed with a hack. I would restructure the code and trim the controller down to one scroll view.

How to alter a button in cell on click in swift ios?

I have a table layout inside a view which as a custom cell,The problem I'm facing is that the cells inside has a button i want to hide the button in cell on clicking it(only the one that is clicked should be hidden) how can i do thing in correct method?
ScrollCell.swift
class ScrollCell: UITableViewCell {
#IBOutlet weak var ProfilePic: SpringImageView!
#IBOutlet weak var UserName: SpringButton!
#IBOutlet weak var Closet: UILabel!
#IBOutlet weak var Style: UILabel!
//------//
#IBOutlet weak var MianImg: UIImageView!
//-------//
#IBOutlet weak var ProductName: UILabel!
#IBOutlet weak var LoveCount: UIButton!
#IBOutlet weak var Discount: UILabel!
#IBOutlet weak var OrginalPrice: UILabel!
#IBOutlet weak var Unliked: UIButton!
#IBOutlet weak var Liked: UIButton!
#IBOutlet weak var Comment: UIButton!
#IBOutlet weak var Share: SpringButton!
override func awakeFromNib() {
super.awakeFromNib()
}
override func setSelected(selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
}
override func layoutSubviews() {
ProfilePic.layer.cornerRadius = ProfilePic.bounds.height / 2
ProfilePic.clipsToBounds = true
}
}
ScrollController.swift
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1 // however many sections you need
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
print(try! Realm().objects(Feed))
var FeedModel = Feed()
let realm = try! Realm()
let tan = try! Realm().objects(Feed).sorted("ID", ascending: false)
return tan.count // however many rows you need
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
// get an instance of your cell
cell = tableView.dequeueReusableCellWithIdentifier("ScrollCellDqueue", forIndexPath: indexPath) as! ScrollCell
IndexPath = indexPath.row
var FeedModel = Feed()
let realm = try! Realm()
let tan = try! Realm().objects(Feed).sorted("ID", ascending: false)
cell.ProfilePic.kf_setImageWithURL(NSURL(string:tan[indexPath.row].ProfilePic)!)
cell.UserName.setTitle(tan[indexPath.row].FullName, forState: .Normal)
cell.Style.text = tan[indexPath.row].StyleType
if tan[indexPath.row].UserType == "store_front"{
cell.Closet.text = "Store Front"
}else if tan[indexPath.row].UserType == "normal"{
cell.Closet.text = "Pri Loved"
}
//-----//
var SingleImage:String = ""
var ImageArray = tan[indexPath.row].ImageArraySet.componentsSeparatedByString(",")
SingleImage = ImageArray[0]
cell.MianImg.kf_setImageWithURL(NSURL(string:SingleImage)!)
//-----//
cell.ProductName.text = tan[indexPath.row].ItemName
cell.OrginalPrice?.text = "\(tan[indexPath.row].OrginalPrice)"
cell.LoveCount.setTitle("\(tan[indexPath.row].LikeCount)"+" Loves", forState: .Normal)
cell.Discount.text = "\(tan[indexPath.row].Discount)"+" % off"
if(tan[indexPath.row].LikeStatus){
cell.Unliked.hidden = true
cell.Liked.hidden = false
}
else if (!tan[indexPath.row].LikeStatus){
cell.Unliked.hidden = false
cell.Liked.hidden = true
}
cell.Unliked.tag = tan[indexPath.row].ID
cell.Liked.tag = tan[indexPath.row].ID
return cell
}
#IBAction func LikeBtn(sender: AnyObject) {
print(sender.tag)
print(IndexPath)
//here i want to know who i can hide the button i have clicked ?
}
Here i want to access the cell in which button is clicked and make changes to UI item inside that cell how can i do that ?
There are many ways to do it. One possible solution is use block.
Add this to ScrollCell
var didLikedTapped: (() -> Void)?
and receive the event of the LikedButton in the cell
#IBAction func LikeBtn(sender: AnyObject) {
didLikedTapped?()
}
Then in cellForRowAtIndexPath of viewController add this
cell.didLikedTapped = {[weak self] in
print(IndexPath)
}
Liked is uibutton in ScrollCell, i don't known, why can you add IBAction for it in ScrollController? . You must implement it in ScrollCell And code:
#IBAction func LikeBtn(sender: UIButton) {
print(sender.tag)
sender.hiden = true
}
And i think, if you have only one UIbutton, it will better. In there, like and unlike is 2 state of uibutton(seleted and none). When you click the button, change it's state
Update:
class sampleCell: UITableViewCell{
#IBOutlet var btnLike : UIButton!
#IBOutlet var btnUnLike : UIButton! // frame of 2 button is equal
override func awakeFromNib() {
super.awakeFromNib()
self.btnUnLike.hidden = true
// ...
}
func updateData(data:AnyObject){ // data's type is Feed
// set data for cell
// i think you should implement in here. and in ScollController call : cell.updateData() , it's better
/* e.x
self.ProductName.text = tan[indexPath.row].ItemName
self.OrginalPrice?.text = "\(tan[indexPath.row].OrginalPrice)"
self.LoveCount.setTitle("\(tan[indexPath.row].LikeCount)"+" Loves", forState: .Normal)
self.Discount.text = "\(tan[indexPath.row].Discount)"+" % off"
*/
}
#IBAction func likeTap(sender:UIButton){ // rememeber set outlet event for btnLike and btnUnLike is this function
if sender == self.btnLike{
self.btnLike.hidden = true
self.btnUnLike.hidden = false
// do s.t
}else if sender == self.btnUnLike{
self.btnLike.hidden = false
self.btnUnLike.hidden = true
// do s.t
}
}
}
Check if the following code help
#IBAction func LikeBtn(sender: AnyObject) {
var position: CGPoint = sender.convertPoint(CGPointZero, toView: self.tableView)
let indexPath = self.tableView.indexPathForRowAtPoint(position)
let cell: UITableViewCell = tableView.cellForRowAtIndexPath(indexPath!)! as
UITableViewCell
print(indexPath?.row)
}
give the LikeBtn the property indexpath, in cellForRowAtIndexPath method, pass the indexPath to the LikeBtn, then you will know which cell's LikeBtn clicked.
class LikeBtn: UIButton {
var indexPath: NSIndexPath?
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("reuseIdentifier", forIndexPath: indexPath)
// here pass the indexpath to your button
cell.likeBtn.indexPath = indexPath
return cell
}
#IBAction func likeTap(sender: LikeBtn){
if let indexPath = sender.indexPath {
if let cell = tableView.cellForRowAtIndexPath(indexPath) {
//here you will know the exact cell, now you can hide or show your buttons
}
}
}

dynamic tableview inside custom tableviewcell

I'm trying to create a tableview with custom cells that each one holds a tableview.
I want to show the inner tableview just when it have some data (most of the time it's empty). I've managed to display the cells but can't display their tableview if it's populated with data.
The problem also is that the cell height needs to be dynamic according to the amount of data to display.
The cell code:
class feedViewCell: UITableViewCell , UITableViewDataSource , UITableViewDelegate {
#IBOutlet var feedCellImage: UIImageView!
#IBOutlet var feedCellUserName: UILabel!
#IBOutlet var feedCellDate: UILabel!
#IBOutlet var feedCellComments: UILabel!
#IBOutlet var cardView: UIView!
#IBOutlet var repliesTableView: UITableView!
var repliesArray:[Reply] = []
#IBAction func addComment(sender: AnyObject) {
}
override func awakeFromNib() {
super.awakeFromNib()
var nib = UINib(nibName: "feedComment", bundle: nil)
repliesTableView.registerNib(nib, forCellReuseIdentifier: "commentCell")
}
override func setSelected(selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
override func layoutSubviews() {
cardSetup()
}
func cardSetup() {
cardView.layer.masksToBounds = false
cardView.layer.cornerRadius = 5
cardView.layer.shadowOffset = CGSizeMake(-0.2, 0.2)
cardView.layer.shadowRadius = 1
cardView.layer.shadowOpacity = 0.2
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return repliesArray.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell = repliesTableView.dequeueReusableCellWithIdentifier("commentCell", forIndexPath: indexPath) as CommentFeedCell
cell.commentCellUserName.text = repliesArray[indexPath.row].userName
return cell
}
}
And the Main controller code:
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var comment = comments[indexPath.row]
let cell: feedViewCell = tableView.dequeueReusableCellWithIdentifier("feedCell", forIndexPath: indexPath) as feedViewCell
cell.feedCellUserName.text = comment.userName
cell.feedCellImage.backgroundColor = UIColor.redColor()
cell.feedCellComments.text = "\(comment.replies.count) COMMENTS"
cell.repliesArray = comment.replies
var dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "dd-MM-yyy"
cell.feedCellDate.text = dateFormatter.stringFromDate(NSDate())
if cell.repliesArray.count > 0 {
cell.repliesTableView.rowHeight = UITableViewAutomaticDimension
}
cell.repliesTableView.reloadData()
return cell
}
How to show the inner tableview only in cells which have comments (and hiding the tableview in cells with 0 comments)?
Call super in layoutSubviews and let us know what happens.
override func layoutSubviews() {
super.layoutSubviews()
cardSetup()
}

UIImageView not showing image in custom UITableViewCell

The UIImageView is not showing the image up in my custom UITableViewCell.
Can't figure out why, I have tried both methods of setting the Image property it in the Interface Builder and then tried setting up an IBOutlet and setting the .image property.
None seem to work. Why is this happening to me?!?!
Class with TableViewDataSource
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell = tableView.dequeueReusableCellWithIdentifier("LatestMessageCell") as LatestMessageCell
cell.avatarImageView.image = UIImage(named: "Logo")
return cell
}
Custom Cell Class
class LatestMessageCell: UITableViewCell {
#IBOutlet weak var cardBackgroundView: UIView!
#IBOutlet weak var avatarImageView: UIImageView!
#IBOutlet weak var usernameLabel: UILabel!
#IBOutlet weak var messageLabel: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
cardBackgroundView.layer.cornerRadius = 4
cardBackgroundView.layer.shadowColor = UIColor.blackColor().CGColor
cardBackgroundView.layer.shadowOffset = CGSize(width: 0, height: 2)
cardBackgroundView.layer.shadowOpacity = 0.3
cardBackgroundView.layer.shadowRadius = 5
}
override func setSelected(selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
Pls modify your Method and check:
let simpleTableIdentifier = "TableViewCell";
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
{
var cell:LatestMessageCell? = tableView.dequeueReusableCellWithIdentifier(simpleTableIdentifier) as? LatestMessageCell
if (cell == nil)
{
let nib:Array = NSBundle.mainBundle().loadNibNamed("LatestMessageCell", owner: self, options: nil)
cell = nib[0] as? LatestMessageCell
}
cell!.avatarImageView.image = UIImage(named: "Logo")
return cell!
}

Changing table from tableviewcontroller to regular view controller

Sorry if this kind of question isn't welcome here but I'd appreciate the help. I have a fully functioning table now set up but I did it using the TableViewController in storyboard. I now realize I cannot change the size of the view using that item and it doesn't fit well on the screen as is. I understand I need to use a regular view controller and add the table view manually. I can do that but I spent hours getting the table to work properly and I'm afraid to break it. Can someone walk me through transitioning between the two?
Here is the storyboard
Here is the view controller code
import UIKit
class CharacterTableViewController: UITableViewController, UITableViewDataSource, UITableViewDelegate {
#IBOutlet var characterTableView: UITableView!
var characterArray: [Character] = [Character]()
override func viewDidLoad() {
super.viewDidLoad()
self.characterSetup()
}
func characterSetup() {
var admiralSwiggins = Character(name: "Admiral Swiggins", abilities: "Stun, Blind, Shield, Damage Over Time, Area of Effect", characterImage: "admiral.png")
var ayla = Character(name: "Ayla", abilities: "Area of Effect, Damage Over Time, Fly, Lifesteal, Shield, Slow", characterImage: "ayla.png")
var clunk = Character(name: "Clunk", abilities: "Lifesteal, Area of effect, Ensnare, Slow, Launch String", characterImage: "clunk.png")
characterArray.append(admiralSwiggins)
characterArray.append(ayla)
characterArray.append(clunk)
}
override func tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell! {
var cell:CharacterTableViewCell = self.tableView.dequeueReusableCellWithIdentifier("Cell") as CharacterTableViewCell
if indexPath.row % 2 == 0 {
cell.backgroundColor = UIColor.redColor()
}
let character = characterArray[indexPath.row]
cell.nameLabel.text = character.name
cell.abilityLabel.text = character.abilities
cell.characterImage.image = UIImage(named: character.characterImage)
return cell
}
override func tableView(tableView: UITableView!, didSelectRowAtIndexPath indexPath: NSIndexPath!) {
}
}
And here is the cell
import UIKit
class CharacterTableViewCell: UITableViewCell {
#IBOutlet var nameLabel: UILabel!
#IBOutlet var abilityLabel: UILabel!
#IBOutlet var characterImage: UIImageView!
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
}
}

Resources