How do I add multiple objects to a table view cell? - ios

How can I add multiple objects in the same cell?
func getNowPlayingItem() {
if let nowPlaying = musicPlayer.nowPlayingItem {
let title = nowPlaying[MPMediaItemPropertyTitle] as? String
let artist = nowPlaying[MPMediaItemPropertyArtist] as? String
let album = nowPlaying[MPMediaItemPropertyAlbumTitle] as? String
println("Song: \(title)")
println("Artist: \(artist)")
println("Album: \(album)")
println("\n")
self.add = [Play(name: title!)]
self.table.rowHeight = UITableViewAutomaticDimension
self.table.estimatedRowHeight = 44.0
}
}
I tried modifying [Play(name: title!)] to [Play(name: title! + artist! + album!)], but only the title shows up, I'm guessing that only the first object will appear. How can I get all three to show up on three separate lines, but in the same cell?

You can use string substitution i.e "\(title!) \(artist!) \(album !)" instead.

In tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell set following property for your UITableViewCell.
cell.textLabel?.numberOfLines = 3;
cell.textLabel?.lineBreakMode = NSLineBreakMode.ByWordWrapping
By default, your UITableViewCell only display the first line of text. So, you need to set numberOfLines to 3.
Then:
self.add = [Play(name: "\(title!)\n\(artist!)\n\(album !)")]
Notice the newline "\n" character.

Related

TableViewCell does not change Label colour

I am facing problem in UITableView. I want change the label color on some condition. But it does not change on first reload. But when I start scrolling the new reusable cell change the text color.
Here is my code
I tried setNeedDesplay() and layoutIfNeeded() but not working either.
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell") as! WalletHistoryCell
let item = array[indexPath.row]
let amountDouble = Float(item.amount ?? "0.0")
cell.labelAmount.text = String.init(format: Constants.AMOUNT_PLACEHOLDER, amountDouble!)
cell.labelDateTime.text = item.dateTime ?? ""
if !(item.details?.isEmpty)!{
cell.labelReason.text = String.init(format: Constants.REASON_PLACEHOLDER, item.details!)
}
if item.debit!{
cell.labelName.text = item.toName ?? ""
cell.labelTo.text = item.toNum ?? ""
cell.labelAmount.textColor = UIColor.appDiscountColor
}else{
cell.labelName.text = item.fromName ?? ""
cell.labelTo.text = item.phoneNumber ?? ""
cell.labelAmount.textColor = UIColor.appHopOrbitColor
}
return cell
}
By default it must work correctly. I.e. the problem not in TableView or TableViewCell. The only reason I can suppose is that tableView.reloadData() calls earlier than array updates. You can recheck this by printing item in cellForRowAt method.

How to make some text or words invisible or visible in the cell?

I would like to make some words in the cell invisible or visible. This is my code below.
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
cell = tableView.dequeueReusableCell(withIdentifier: "cell") as? TableViewCell
var dic = ar[indexPath.row]
cell!.cell0.text = dic["date0"]
...
cell!.cell0.text has "Helloworld"
I need "Helloworld" for later so I can't get only "world" from dic["date0"].
I would like to make only "world" visible in the table view.
Is there anyone who can help me out?
Thanks!
What you are looking for are Substrings.
let string = "Helloworld"
let beginningText = String(string.suffix(5)) //world
let endText = String(string.prefix(5)) //Hello
let start = string.index(string.startIndex, offsetBy: 1)
let end = string.index(string.endIndex, offsetBy: -3)
let range = start..<end
let middleText = String(string[range]) //ellowo
For more information, refer to this answer on a different question: Link
In the cell class you can so like so:
var str = "Helloworld"// for example
var splitString = str.components(separatedBy: "Hello")
self.label.text = splitString
Check out isHidden
With isHiddem you can choose with a Boolean value if you want to show the text or not
https://developer.apple.com/documentation/uikit/uiview/1622585-ishidden

How to hide empty cell tableview, which are not at the end? Swift 3

I'm just starting swift and I'm making a calendar app. Right now I'm showing a list on events if you click on a date. All questions here are about hiding cells that are at the end of a tablieview, but mine are not so eventsTableView.tableFooterView = UIView() doesn't work.
override func viewDidLoad() {
super.viewDidLoad()
eventsTableView.register(UITableViewCell.self, forCellReuseIdentifier: "theCell")
self.eventsTableView.rowHeight = 80
}
func tableView(_ eventsTableView: UITableView,
cellForRowAt indexPath: IndexPath)->UITableViewCell{
let event = model.events[indexPath.row]
let theItem = eventsTableView.dequeueReusableCell(
withIdentifier: "theCell",for: indexPath)
let what = event.value(forKeyPath:"what") as? String
let location = event.value(forKeyPath:"location") as? String
let when = event.value(forKeyPath:"when") as? Date
if model.checkDay(date: when!) == model.givendate && model.checkMonth(date: when!) == model.displayedMonth {
theItem.textLabel?.numberOfLines = 3
let labelText = what! + "\n" + "time: " + model.getTime(date: when!) + "\n" + "location: " + location!
theItem.textLabel?.text = labelText
} else {
theItem.textLabel?.numberOfLines = 0
}
print(theItem)
return theItem
}
This is what my output looks like
Try this code :
You can put a check for empty data in a model and hide that cell completely like this:
override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
//Check if model is empty
if shouldHideCell {
return 0
} else {
return UITableViewAutomaticDimension
}
}
Please refer to this SO Post. Happy coding.
What you can do here is just customise your dataSource, like if the Data corresponding to that row is empty then it's better to not to add that row in your datasource array.
Example while customising your dataSource
if hasEvent{
dataSource.append(day)
}else{
// No need to show in UI
}

First cell wrong size

I need to get the first cell in my tableView to be a different size from the rest. The rest of my cells are all under the class CustomPFTableViewCell, but the first one is a different cell so its under the class FirstPFTableViewCell, both of which extend from the class PFTableViewCell. Right now, I just used an if depending on the indexPath.row for whether or not the cell was the first cell. When its not it will load data for the cell from Parse.
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath, object: PFObject?) -> PFTableViewCell {
if(indexPath.row >= 1){
let cell = tableView.dequeueReusableCellWithIdentifier("Cell") as! CustomPFTableViewCell!
print("Loading Parse Database Files...")
// Extract values from the PFObject to display in the table cell
if let name = object?["Name"] as? String {
cell?.nameTextLabel?.text = name
print("Loading " + name)
}
if let author = object?["authorName"] as? String {
cell?.authorTextLabel?.text = author
}
if let likes = object?["Likes"] as? Int {
let stringVal = String(likes)
cell?.numLikes.text = stringVal
}
if let descrip = object?["Description"] as? String {
cell?.descriptionHolder = descrip
}
let initialThumbnail = UIImage(named: "Unloaded")
cell.customFlag.image = initialThumbnail
if let thumbnail = object?["imageCover"] as? PFFile {
cell.customFlag.file = thumbnail
cell.customFlag.loadInBackground()
}
return cell
}
print("Finished loading!")
let cell = tableView.dequeueReusableCellWithIdentifier("firstCell") as! PFTableViewCell
return cell
}
The end is empty because I'm not sure how to go about changing the one/first cell's size. (In the Interface Builder its set to 60). I guess the most important part in solving this is this:
let cell = tableView.dequeueReusableCellWithIdentifier("firstCell") as! PFTableViewCell
return cell
}
In order to play with the size of the cell you have to implement the UITableViewDelegate function
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
if indexPath.row == 0 {
return firstCellHeight
} else {
return customCellHeight
}

Dynamic tableView Cell height swift IOS8

I'm trying to create tableView which is suppose to auto resize the height according to the messageLabel. IOS8 has made this a lot of easier, however i can't seem to achieve this. So far i've created tableViewCell custom class with a xib file looking like below:
and then set the messageLabel.numberOfLines = 0
in the viewController i've set following in viewDidLoad
tableView.estimatedRowHeight = 80.0
tableView.rowHeight = UITableViewAutomaticDimension
and in the end the delegate methods
func tableView(tableView:UITableView, numberOfRowsInSection section:Int)->Int
{
return 1
}
func numberOfSectionsInTableView(tableView:UITableView)->Int
{
return 1
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
{
var cell = tableView.dequeueReusableCellWithIdentifier("TwitterPlainCell", forIndexPath: indexPath) as! TwitterPlainCell
let url = NSURL(string: "https://pbs.twimg.com/profile_images/507493048062713856/KaWKfdgW.jpeg")
let data = NSData(contentsOfURL: url!) //make sure your image in this url does exist, otherwise unwrap in a if let check
cell.selectionStyle = UITableViewCellSelectionStyle.None
// cell.backgroundColor = UIColor(rgba: "#f6f7f9")
var name = "Olof Kajbjer"
var userName = "#olofmCS"
var topText = "\(name) \(userName)"
var topCount = count(topText)
var userCount = count(userName)
var userNameLocation = topCount - userCount
cell.profileImage.image = UIImage(data: data!)
cell.dateLabel.text = "55m"
var myMutableString = NSMutableAttributedString(string: topText, attributes: [NSFontAttributeName:UIFont(name: "PT Sans", size: 18.0)!])
myMutableString.addAttribute(NSForegroundColorAttributeName, value: UIColor(rgba: "#A6B0B5"), range: NSRange(location:userNameLocation,length:count(userName)))
myMutableString.addAttribute(NSFontAttributeName, value: UIFont(name: "PT Sans", size: 13)!, range: NSRange(location:userNameLocation,length:count(userName)))
// set label Attribute
cell.topLabel.attributedText = myMutableString
cell.messageLabel.text = "I FUCKING LOST AGAINST #olofmCS ON AIM AWP IN OVERTIME... GGgg"
cell.setNeedsUpdateConstraints()
cell.updateConstraintsIfNeeded()
return cell
}
The result of this can seen below, why is it not resizing the cell height?
The issue was related to the bottom constraint i had to set it to >= or another value

Resources