How to Display Current location on tableViewCell in iOS - ios

I want to Display current location Address on a TableViewCell. I got the latitude and longitude but i can't understand how to show address string on cell.
i wrote the below code in ViewDidLoad()
it display the address in label.
let manager: CLLocationManager = locationManager
CLGeocoder().reverseGeocodeLocation(manager.location!, completionHandler: {(placemarks, error)->Void in
let placemark = placemarks?[0]
let lines = placemark?.addressDictionary?["FormattedAddressLines"]
let addressString = (lines as! NSArray).componentsJoined(by: "\n")
self.lblAddress.text = addressString
print(addressString)
})
but i want to show the address on tableview Cell.
//return cell for perticular row withing section
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
{
if indexPath.section <= 1
{
let cell = tableView.dequeueReusableCell(withIdentifier: "CellRID", for: indexPath)
cell.textLabel?.text = "\(self.batteryLevel() * 100) %"
return cell
}
else
{
//create reusable cell object by dequeueReusableCellWithIdentifier
//identifier must register with cell
let cell = tableView.dequeueReusableCell(withIdentifier: "LocationTableViewCellRID", for: indexPath) as! LocationTableViewCell
let personName = txtFieldName.text
let a = LocationVC()
cell.lblName?.text = "\(personName) \(self.batteryLevel() * 100) %"
cell.lblAddress?.text =
return cell
}
}
I want to show the address on lblAddress. I am new to iOS. Thanks in Advance for you help.

You should have declared a property for addressString above the viewDidLoad method. Not inside the viewDidLoad method.
Add this above the viewDidLoad method
let addressString = String()
Then in the viewDidLoad method change this line
let addressString = (lines as! NSArray).componentsJoined(by: "\n")
to
self.addressString = (lines as! NSArray).componentsJoined(by: "\n")

If you make your addressString a property, you would have access to it in cellRowForAtIndexPath.

Related

How to work with the Cosmo Raiting Library in table cells? (SWIFT)

I don't understand how to link the selection of a set of rating stars to each cell and save this value?
Cosmo lib: https://github.com/evgenyneu/Cosmos
My Code:
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "CustomCell", for: indexPath) as! CustomCellTableViewCell
let currentNameItem = gameNameArray[indexPath.row]
cell.gameNameLabel?.text = currentNameItem["Name"] as? String
// MARK: - переменная из словаря - если true ставим галочку - если нет убираем
if (currentNameItem["isCompleted"] as? Bool) == true {
cell.accessoryType = .checkmark
} else {
cell.accessoryType = .none
}
let currentSubNameItem = gameSubNameArray[indexPath.row]
cell.subGameNameLabel?.text = currentSubNameItem["Name"] as? String
let currentScoreItem = gameScoreArray[indexPath.row]
cell.gameScoreValue?.text = currentScoreItem["Name"] as? String
let currentImageItem = gameImageArray[indexPath.row]
guard let url = URL(string: currentImageItem["Name"] as! String) else { return cell }
cell.gameImage.sd_setImage(with: url, completed: nil)
//I can set the rating value
cell.fiveStarRaiting.rating = 5
let currentRaitingItem = raitingArray[indexPath.row] //array where I would like to save the ratings
cell.fiveStarRaiting.rating = currentRaitingItem //here, the values from the rating array should be pulled up by the ide
//allows you to save the rating value at the end of the finger movement gesture
cell.fiveStarRaiting.didFinishTouchingCosmos = { [self] raiting in raitingArray.append(raitingStarValue)}
print(raitingArray.count)
//cell.testButton0.addTarget(self, action: #selector(testFuncButton(sender:)), for: .touchUpInside)
return cell
}
As you know, table view cells are reusable, so when you scrolls and when cells are disappeared then its values are also cleared that's how table view and collection view works.
So if you want to save those ratings then you can go with a local temporary dictionary.
e.g.
var ratingsArray = [Int:Float]()
store your indexpath as key in "ratingsArray" dictionary and set its value as cosmos ratings.
and set cosmos ratings values as prefill in "cellForRowAt" table view method,
if ratingsArray.keys.contains(indexPath.row) {
cell.fiveStarRaiting.rating = 5
}
else {
cell.fiveStarRaiting.rating = 0 // set starts default value here
}
cell.fiveStarRaiting.didFinishTouchingCosmos = { [self] rating in
ratingsArray[indexPath.row] = rating
}

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 give more than 2 custom cell on one tableView for chat

chat image for chat ui have 3 type which is text , image , and carousel . am i need to make 3 custom cell for one tableView and how to do that ?
Yes you have to create three custom cell, for crousal either use third party or a collection view inside tableview cell.
for eg:
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cellIncomming = tableView.dequeueReusableCell(withIdentifier: "IncommingChatCell") as! IncommingChatCell
let cellOutgoing = tableView.dequeueReusableCell(withIdentifier: "OutgoingChatCell") as! OutgoingChatCell
let chatInfo = chatDataSourse[indexPath.row]
if chatInfo.user == "receiver" {
cellIncomming.chatLabel.text = chatInfo.chatString
return cellIncomming
}else {
cellOutgoing.chatLabel.text = chatInfo.chatString
return cellOutgoing
}
}
in cellforrow
if Condition1 {
let cell : CellOne! = tableView.dequeueReusableCell( withIdentifier: "CellOne") as? CellOne
return cell
}else if Condition2{
let cell : CellTwo! = tableView.dequeueReusableCell( withIdentifier: "CellTwo") as? CellTwo
return cell
}else{
let cell : CellThree! = tableView.dequeueReusableCell( withIdentifier: "CellThree") as? CellThree
return cell
}

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
}

Why is my SearchController not displaying the correct cell prototype for the first cell?

As the title suggests, I am having trouble with my UISearchController displaying the wrong cell prototype for the first cell in the search results.
Background Information: I have two cell prototypes, one without an image (identifier: basicCell) and another with a UIImageView (identifier: imageCell). Cells work perfectly when not searching.
Detailed Description of the Problem: When I click on the search bar everything is fine until I start searching for something. When I do, the first cell always has the imageCell identifier (a gray empty image view is shown denoting the lack of an image), no matter what. NB: Before searching anything, the first cell in the tableview has a custom image... Maybe that's of note?
Anyway I have no idea what I am doing wrong. Would anyone mind helping?
Code:
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
if (self.resultSearchController.active) {
if hasImageAtIndexPath(indexPath) {
let cell = tableView.dequeueReusableCellWithIdentifier(imageCellIdentifier, forIndexPath: indexPath) as! TimelineTableViewCellImage
let event = filteredTableData[indexPath.row]
cell.content.text = profile.content
cell.name.text = profile.name
//This is the image
cell.attachment.image = profile.image
cell.attachment.layer.cornerRadius = 1
cell.attachment.clipsToBounds = true
return cell
} else {
let cell = tableView.dequeueReusableCellWithIdentifier(basicCellIdentifier, forIndexPath: indexPath) as! TimelineTableViewCell
let event = filteredTableData[indexPath.row]
cell.content.text = profile.content
cell.name.text = profile.name
return cell
}
} else {
if hasImageAtIndexPath(indexPath) {
let cell = tableView.dequeueReusableCellWithIdentifier(imageCellIdentifier, forIndexPath: indexPath) as! TimelineTableViewCellImage
let event = events[indexPath.row]
cell.content.text = profile.content
cell.name.text = profile.name
cell.attachement.image = profile.image
cell.attachment.layer.cornerRadius = 1
cell.attachment.clipsToBounds = true
return cell
} else {
let cell = tableView.dequeueReusableCellWithIdentifier(basicCellIdentifier, forIndexPath: indexPath) as! TimelineTableViewCell
let event = events[indexPath.row]
cell.content.text = profile.content
cell.name.text = profile.name
return cell
}
}
}
And this is my code that checks for an image:
func hasImageAtIndexPath(indexPath:NSIndexPath) -> Bool {
let event = events[indexPath.row]
let imageArray = [event.image]
for eventImage in imageArray {
if eventImage != nil {
return true
}
}
return false
}
You need to have an if-else clause in your hasImageAtIndexPath: function just like you have in your cellForRowAtIndexPath:. If the table view is the search table, then event needs to be defined the same way as you have in cellForRowAtIndexPath:,
func hasImageAtIndexPath(indexPath:NSIndexPath sender:UITableView) -> Bool
if (self.resultSearchController.active){
let event = filteredTableData[indexPath.row]
}else{
let event = events[indexPath.row]
}
let imageArray = [event.image]
for eventImage in imageArray {
if eventImage != nil {
return true
}
}
return false
}

Resources