Greetings I have the disadvantage that the cells of the tableview are duplicated in a random way, at certain times the event occurs, not always
i think i need to clean or reload data but im not sure, could you help please.
final class MovementsDatasource: NSObject, PaginatedDatasource {
typealias Values = MovementsSectionModel
private let repository: TransactionsRepositoryProtocol
private let disposeBag = DisposeBag()
private let fetching = ActivityIndicator()
private let id: String, cvl: String
private let rowsObserver = PublishSubject<[Values]>()
var values = [Values]() { didSet { self.rowsObserver.onNext(self.values) } }
var page = 0
var hasNextPage = false
init(repository: TransactionsRepositoryProtocol, id: String, cvl: String) {
self.id = id
self.cvl = cvl
self.repository = repository
}
func getActivityIndicator() -> ActivityIndicator { self.fetching }
func getValuesObserver() -> Observable<[Values]> { self.rowsObserver }
func getNextPage() {
guard self.hasNextPage else { return }
getMovements(for: self.id, cvl: self.cvl, page: self.page)
}
func getFirstPage() {
self.page = 0
self.hasNextPage = false
self.values = []
getMovements(for: self.id, cvl: self.cvl, page: self.page)
}
}
extension MovementsDatasource {
private func getMovements(for productID: String, cvl: String, page: Int) {
self.repository
.movements(userCVL: cvl, ibanAccountId: productID, page: page)
.trackActivity(self.fetching)
.subscribe(onNext: { [weak self] response in
guard let _self = self else { return }
_self.hasNextPage = response.hasNextPage
_self.page = _self.hasNextPage ? (_self.page + 1) : _self.page
_self.publish(response)
})
.disposed(by: self.disposeBag)
}
private func publish(_ response: MovementsResponse) {
guard let rawMovement = response.values else { return }
let newRows = self.transform(rawMovement)
var rows = self.values
if !rows.isEmpty { rows += newRows }
else { rows = newRows }
self.values = self.merge(rows)
}
internal func transform(_ movements: [Movement]) -> [MovementsSectionModel] {
movements
.map { $0.movementDate.displayTimestamp() }
.unique()
.map { title -> MovementsSectionModel in
let sorted = movements.filter { $0.movementDate.displayTimestamp() == title }
return MovementsSectionModel(header: title, items: sorted)
}
}
internal func merge(_ sections: [MovementsSectionModel]) -> [MovementsSectionModel] {
sections
.map { $0.header }
.unique()
.map { title -> MovementsSectionModel in
let merged = sections.reduce(into: [MovementCellViewModel]()) {
accumulator, section in
if section.header == title { accumulator += section.items }
}
return MovementsSectionModel(header: title, items: merged)
}
}
}
extension MovementsDatasource {
func tableView(_: UITableView, numberOfRowsInSection section: Int) -> Int {
self.values[section].items.count
}
func numberOfSections(in _: UITableView) -> Int { self.values.count }
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
guard !self.values.isEmpty, let cell = tableView.dequeueReusableCell(withIdentifier: MovementCell.reuseID, for: indexPath) as? MovementCell
else {
return UITableViewCell(frame: .zero)
}
let section = indexPath.section
let index = indexPath.item
if !self.values.isEmpty {
cell.viewModel = self.values[section].items[index]
}
return cell
}
}
Related
I have a table view with header as title for two offers.
Offers for standard routes as 1 euro offers
Offers for alternative routes as nearby offers
I have a search bar to search offers from tableview and load in table rows.I want to show both offers in two sections as section 1 with standard route offer and section 2 with nearby offers. The problem is I am getting only one section with header as standard offers or nearby offers which one is being searched in tableview. How I can get two sections with title for both standard and nearby offers. Here is my code. Two array for offers as:
struct AlternativeRoutesResponse: Codable {
let nearbyRoutes: [AlternativeRouteOffer]
let standardRoutes: [AlternativeRouteOffer]
var nearbyRoutesSection: SearchSection? {
nearbyRoutes.isEmpty ? nil : SearchSection(title: L10n.Search.nearbyOffers, offers: nearbyRoutes.map({RouteOffer(alternativeOffer: $0)}))
}
var standardRoutesSection: SearchSection? {
standardRoutes.isEmpty ? nil : SearchSection(title: L10n.Search.standardOffers, offers: standardRoutes.map({RouteOffer(alternativeOffer: $0, isStandard: true)}))
}
}
Offers parameters:
struct AlternativeRouteOffer: Codable {
struct LocationOffer: Codable {
let name: String
let thingId: Int
}
let departure: LocationOffer
let destination: LocationOffer
}
In search model:
struct OffersResponse {
let status: Bool
let sections: [SearchSection]
let title: String
}
enum SearchOffersDetailsEvent: Event {
case nothingFoundAt(date: Date, offer: RouteOffer)
}
enum SearchOffersEvent: Event {
case setAlert(departure: AddressLocation?, destination: AddressLocation?)
}
enum SearchOffersModelAction {
case exchangeLocations
case setAlert
}
protocol SearchOffersModelInput: AnyObject {
var numberOfSections: Int { get }
var isGuest: Bool { get }
func send(action: SearchOffersModelAction)
func load()
func itemsIn(section: Int) -> Int
func configureCell(for tableView: UITableView, at indexPath: IndexPath) -> UITableViewCell
func didSelect(indexPath: IndexPath)
func headerIn(section: Int, for tableView: UITableView) -> UITableViewHeaderFooterView?
func heightForHeader(in section: Int) -> CGFloat
}
protocol SearchOffersModelOutput: AnyObject {
func didLoad()
func pop()
}
final class SearchOffersModel: TextFieldEventNode {
enum StateResult {
case isFound, noResults, empty
var headerItemsCount: Int {
switch self {
case .empty: return 2
case .noResults: return 3
default: return 2
}
}
func cellReuseIdentifierFor(row: Int) -> String {
switch self {
default:
switch row {
case 0: return SearchRoutesHeaderTableViewCell.className
case 1: return SearchResultInfoTableViewCell.className
case 2: return SearchPlaceholderTableViewCell.className
default: return ""
}
}
}
}
enum SearchTableSection: Int {
case searchHeader = 0
case results = 1
}
weak var output: SearchOffersModelOutput!
private let offersProvider = DataManager<RoutesAPI, SearchRoutesResponse>()
private let alternativeOffersProvider = DataManager<RoutesAPI, AlternativeRoutesResponse>()
private let routesDetailsProvider = DataManager<RoutesAPI, [OfferDetails]>()
private let alternativeRoutesDetailsProvider = DataManager<RoutesAPI, [OfferDetails]>()
private let searchData: SearchRoutesData
private var sections: [SearchSection] {
[data?.searchSection, alternativeData?.nearbyRoutesSection, alternativeData?.standardRoutesSection].compactMap({$0})
}
private var state = StateResult.empty
private var data: SearchRoutesResponse?
private var alternativeData: AlternativeRoutesResponse?
init(parent: EventNode?, data: SearchRoutesData) {
searchData = data
super.init(parent: parent)
addHandler(.onPropagate) {[weak self] (event: SearchOffersDetailsEvent) in
switch event {
case .nothingFoundAt(let date, let offer):
self?.searchData.date = date
self?.searchData.departure = offer.departure
self?.searchData.destination = offer.destination
self?.data = nil
self?.state = .noResults
self?.output.pop()
self?.output.didLoad()
self?.load()
}
}
}
override func didChange(_ textField: TextField) {
switch textField.fieldType {
case .departureCity:
searchData.departure = textField.addressLocation
updateResults()
case .destinationCity:
searchData.destination = textField.addressLocation
updateResults()
case .selectDate:
searchData.date = textField.date
updateResults()
default: break
}
}
func updateResults() {
alternativeData = nil
guard searchData.isEmpty == false, searchData.departure != nil || searchData.destination != nil else {
state = .empty
data = nil
output.didLoad()
return
}
offersProvider.load(target: .offers(parameters: searchData.apiParameters), withActivity: true) {[weak self] result in
switch result {
case .success(let response):
self?.didRecive(response)
case .failure(let error):
print(error.localizedDescription)
}
}
}
private func didRecive(_ response: SearchRoutesResponse) {
data = response
if response.isFound {
alternativeData = nil
state = .isFound
if let o = response.section.offers.first {
loadAlternatives()
load(route: o)
}
} else {
if searchData.isEmpty {
state = .empty
} else if response.section.offers.isEmpty {
loadAlternatives()
} else {
state = .isFound
}
}
output.didLoad()
}
private func loadAlternatives() {
var target: RoutesAPI!
if let departure = searchData.departure?.id, let destination = searchData.destination?.id {
target = .alternative(departure: departure, destination: destination, date: searchData.date)
} else if let departure = searchData.departure?.id {
target = .alternativeDeparture(departure: departure, date: searchData.date)
} else if let destination = searchData.destination?.id {
target = .alternativeDestination(destination: destination, date: searchData.date)
} else {
state = .noResults
output.didLoad()
return
}
alternativeOffersProvider.load(target: target, withActivity: true) {[weak self] result in
switch result {
case .success(let response):
self?.didReciveAlternative(response)
case .failure(let error):
print(error)
}
self?.output.didLoad()
}
}
private func didReciveAlternative(_ response: AlternativeRoutesResponse) {
alternativeData = response
if sections.isEmpty {
state = .noResults
} else {
state = .isFound
}
}
}
extension SearchOffersModel: SearchOffersViewControllerOutput {
var isGuest: Bool {
isAuthorized == false
}
func send(action: SearchOffersModelAction) {
switch action {
case .exchangeLocations:
let departure = searchData.departure
searchData.departure = searchData.destination
searchData.destination = departure
data = nil
alternativeData = nil
output.didLoad()
updateResults()
case .setAlert:
if isAuthorized {
raise(event: SearchOffersEvent.setAlert(departure: searchData.departure, destination: searchData.destination))
} else {
raise(event: UserSessionEvent.setSession(nil))
}
}
}
var searchDataDisplayable: SearchRoutesData {
searchData
}
private var topTitleText: String {
switch state {
case .noResults:
return ""
default:
return searchData.isEmpty ? L10n.Search.emptySearch : data?.title ?? ""
}
}
private var emptyPlaceholderText: String {
if searchData.departure != nil && searchData.destination == nil {
if isAuthorized {
return L10n.Home.enterDestinationCity
} else {
return L10n.Home.guestEnterDestinationCity
}
} else if searchData.destination != nil && searchData.departure == nil {
if isAuthorized {
return L10n.Home.enterDepartureCity
} else {
return L10n.Home.guestEnterDepartureCity
}
} else {
return L10n.Home.noResults
}
}
func load() {
updateResults()
}
func configureCell(for tableView: UITableView, at indexPath: IndexPath) -> UITableViewCell {
switch indexPath.section {
case SearchTableSection.searchHeader.rawValue:
let cell = tableView.dequeueReusableCell(withIdentifier: state.cellReuseIdentifierFor(row: indexPath.row))
switch cell {
case cell as? SearchRoutesHeaderTableViewCell:
let c = cell as? SearchRoutesHeaderTableViewCell
apply([c?.departureTextField, c?.destinationTextField, c?.dateTextField].compactMap({$0}))
c?.apply(searchData: searchData)
return c!
case cell as? SearchResultInfoTableViewCell:
(cell as? SearchResultInfoTableViewCell)?.apply(isFound: data?.isFound ?? false, text: topTitleText)
return cell!
case cell as? SearchPlaceholderTableViewCell:
(cell as? SearchPlaceholderTableViewCell)?.apply(text: emptyPlaceholderText)
return cell!
default:
return cell!
}
default:
let cell = tableView.dequeueReusableCell(withIdentifier: SearchItemTableViewCell.className) as? SearchItemTableViewCell
if !sections.isEmpty {
cell?.apply(DisplayableRouteOffer(offer: sections[indexPath.section - 1].offers[indexPath.row]))}
return cell!
}
}
var numberOfSections: Int {
sections.count + 1
}
func itemsIn(section: Int) -> Int {
switch section {
case SearchTableSection.searchHeader.rawValue: return state.headerItemsCount
default: return sections[section - 1].offers.count
}
}
func headerIn(section: Int, for tableView: UITableView) -> UITableViewHeaderFooterView? {
let h = tableView.dequeueReusableHeaderFooterView(withIdentifier: SearchSectionHeaderTableViewCell.className)
if !sections.isEmpty{
(h as? SearchSectionHeaderTableViewCell)?.apply(title: sections[section - 1].title)
}
return h
}
func heightForHeader(in section: Int) -> CGFloat {
return section == 0 ? 0.0 : 20.0
}
func didSelect(indexPath: IndexPath) {
guard indexPath.section > 0 else { return }
let section = sections[indexPath.section - 1]
var offer = section.offers[indexPath.row]
offer.selectedDate = searchData.date
if offer.isStandard {
loadStandard(route: offer)
} else {
load(route: offer)
}
}
private func loadStandard(route: RouteOffer) {
routesDetailsProvider.load(target: .standardRouteDetails(departure: route.departure.id, destination: route.destination.id, date: searchData.date), withActivity: true) {[weak self] result in
switch result {
case .success(let response):
self?.raise(event: PopularRoutesEvent.openDetails(details: response, offer: route))
case .failure(let error):
print(error)
}
}
}
private func load(route: RouteOffer) {
routesDetailsProvider.load(target: .routeDetails(departure: route.departure.id, destination: route.destination.id, date: searchData.date), withActivity: true) {[weak self] result in
switch result {
case .success(let response):
self?.raise(event: PopularRoutesEvent.openDetails(details: response, offer: route))
case .failure(let error):
print(error)
}
}
}
}
The default offers are as when no offer found it should load default offers
struct SearchRoutesResponse: Codable {
var title: String
var isFound: Bool
var section: SearchSection
var searchSection: SearchSection? {
section.offers.isEmpty ? nil : SearchSection(title: L10n.Search.defaultOffers, offers: section.offers)
}
}
struct SearchSection: Codable {
let title: String
let offers: [RouteOffer]
}
// From Route Offer it should decode data from api as
struct DisplayableRouteOffer {
var fromName: String
var toName: String
var description: String
init(offer: RouteOffer) {
fromName = offer.fromName ?? ""
toName = offer.toName ?? ""
description = "\(offer.distance ?? 0) km, ca. \(offer.amountOfTime ?? "")"
}
}
struct RouteOffer: Codable, Equatable {
struct Location: Codable, Equatable {
let id: Int
}
// Table view method is as here called in viewcontroller
extension SearchOffersViewController: SearchOffersViewControllerInput {
func didLoad() {
tableView.reloadData()
}
func pop() {
navigationController?.popToViewController(self, animated: true)
}
}
extension SearchOffersViewController: UITableViewDataSource {
func numberOfSections(in tableView: UITableView) -> Int {
model.numberOfSections
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
model.itemsIn(section: section)
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
model.configureCell(for: tableView, at: indexPath)
}
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
model.headerIn(section: section, for: tableView)
}
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
model.heightForHeader(in: section)
}
}
extension SearchOffersViewController: UITableViewDelegate {
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
model.didSelect(indexPath: indexPath)
}
}
Simple solution is force numberOfSections to 2.
func numberOfSections(in tableView: UITableView) -> Int {
return 2
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if section == 0{
return standardRoutesSection.count
}else{
return nearbyRoutesSection.count
}
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if section == 0{
let data = standardRoutesSection[index.row]
return UITableViewCell()
}else{
let data = nearbyRoutesSection[index.row]
return UITableViewCell()
}
}
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
if section == 0{
//standar header
}else{
//nearby header
}
return nil
}
How can I update/add/delete an item on a table view with sections and its source?
Im having issues when trying to update a cell. Sometimes it happens on delete and add too.
It seems that a problem on sections is triggering it.
1- Data is loaded from a JSON response from a server.
2 - This data is sorted alphabetically and sections based on the first letter from the name is created adding each client to its indexed letter.
Im adding to print-screens:
Before:
After:
I renamed 'Bowl' to 'Bowl 2' and it 'created' a new entry, keeping the old and new value. If I refresh (pull), it gets fixed.
Also, sometimes, it removes 'Abc MacDon' and after refreshing, it gets fixed.
class ClientsViewController: UITableViewController {
var sortedFirstLetters: [String] = []
var sections: [[Client]] = [[]]
var tableArray = [Client]()
var client: Client?
var wasDeleted: Bool?
var refresher: UIRefreshControl!
#IBOutlet weak var noClientsLabel: UILabel!
#IBOutlet var noClientsView: UIView!
#IBAction func unwindToClients(sender: UIStoryboardSegue) {
if let sourceViewController = sender.source as? ClientViewController,
let client = sourceViewController.client,
let wasDeleted = sourceViewController.wasDeleted {
if(wasDeleted) {
if let selectedIndexPath = tableView.indexPathForSelectedRow {
print("Delteted")
tableArray.remove(at: selectedIndexPath.row)
// DispatchQueue.main.async {
// // Deleting the row in the tableView
// if self.tableView.numberOfRows(inSection: selectedIndexPath.section) > 1 {
// self.tableView.deleteRows(at: [selectedIndexPath], with: UITableViewRowAnimation.bottom)
// } else {
// let indexSet = NSMutableIndexSet()
// indexSet.add(selectedIndexPath.section)
// self.tableView.deleteSections(indexSet as IndexSet, with: UITableViewRowAnimation.bottom)
// }
//
// }
}
}
else {
if let selectedIndexPath = tableView.indexPathForSelectedRow {
// Update an existing client.
tableArray[selectedIndexPath.row] = client
//tableView.reloadRows(at: [selectedIndexPath], with: .automatic)
print("update")
print(tableArray)
}
else {
// Add a client.
tableArray.append(client)
print("add")
}
}
self.prepareData()
DispatchQueue.main.async {
self.tableView.reloadData()
}
}
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
let secondScene = segue.destination as! ClientViewController
if segue.identifier == "ShowDetail", let indexPath = self.tableView.indexPathForSelectedRow {
let currentPhoto = sections[indexPath.section][indexPath.row]
secondScene.client = currentPhoto
}
else if segue.identifier == "AddItem" {
print("add")
}
else {
fatalError("The selected cell is not being displayed by the table")
}
}
#objc func handleRefresh(_ refreshControl: UIRefreshControl) {
getClients()
}
}
extension ClientsViewController {
override func viewDidLoad() {
super.viewDidLoad()
self.refreshControl?.addTarget(self, action: #selector(ClientsViewController.handleRefresh(_:)), for: UIControlEvents.valueChanged)
tableView.backgroundView = nil
noClientsLabel.text = ""
getClients() //for only the 1st time ==> when view is created ==> ok ish
}
override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
if(self.tableArray.count > 0) {
return sortedFirstLetters[section]
}
else {
return ""
}
}
override func sectionIndexTitles(for tableView: UITableView) -> [String]? {
return sortedFirstLetters
}
override func numberOfSections(in tableView: UITableView) -> Int {
return sections.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let item = sections[indexPath.section][indexPath.row]
let cell = tableView.dequeueReusableCell(withIdentifier: "ClientCell", for: indexPath)
cell.textLabel?.text = item.name
cell.detailTextLabel?.text = item.city + " - " + item.province
return cell
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return sections[section].count
}
func getClients() {
print("called server")
self.refreshControl?.beginRefreshing()
self.tableView.setContentOffset(CGPoint(x:0, y:-100), animated: true)
makeRequest(endpoint: "api/clients/all",
parameters: [:],
completionHandler: { (container : ApiContainer<Client>?, error : Error?) in
if let error = error {
print("error calling POST on /getClients")
print(error)
return
}
self.tableArray = (container?.result)!
self.prepareData()
DispatchQueue.main.async {
if(self.tableArray.isEmpty)
{
self.noClientsLabel.text = "bNo Clients"
self.tableView.backgroundView?.isHidden = false
self.noClientsLabel.text = ""
print("all")
}
else{
print("nothing")
}
self.tableView.reloadData()
self.refreshControl?.endRefreshing()
}
} )
}
//sorts and makes the index
func prepareData() {
let firstLetters = self.tableArray.map { $0.nameFirstLetter }
let uniqueFirstLetters = Array(Set(firstLetters))
self.sortedFirstLetters = uniqueFirstLetters.sorted()
self.sections = self.sortedFirstLetters.map { firstLetter in
return self.tableArray
.filter { $0.nameFirstLetter == firstLetter }
.sorted { $0.name < $1.name }
}
}
}
Struct
struct Client: Codable {
var client_id: Int!
let name: String!
let postal_code: String!
let province: String!
let city: String!
let address: String!
init(name: String, client_id: Int! = nil, postal_code: String, province: String, city: String, address: String) {
self.client_id = client_id
self.name = name
self.postal_code = postal_code
self.province = province
self.city = city
self.address = address
}
var nameFirstLetter: String {
return String(self.name[self.name.startIndex]).uppercased()
}
}
code after some interaction with Hardik
import UIKit
import Foundation
class ClientsViewController: UITableViewController {
var sortedFirstLetters: [String] = []
var sections: [[Client]] = [[]]
// var tableArray = [Client]()
var tableArray : [Client] = [Client]()
var client: Client?
var wasDeleted: Bool?
var refresher: UIRefreshControl!
#IBOutlet weak var noClientsLabel: UILabel!
#IBOutlet var noClientsView: UIView!
#IBAction func unwindToClients(sender: UIStoryboardSegue) {
if let sourceViewController = sender.source as? ClientViewController,
let client = sourceViewController.client,
let wasDeleted = sourceViewController.wasDeleted {
if(wasDeleted) {
if let index = self.tableArray.index(where: { (item) -> Bool in
item.client_id == client.client_id
}) {
self.tableArray.remove(at: index)
print("Delteted")
// Find the client in the tableArray by the client id and remove it from the tableArray
// I am writing an example code here, this is not tested so just get the logic from here.
//self.tableArray.remove(at: selectedIndexPath.row)
}
}
else {
if self.tableArray.contains(where: { (item) -> Bool in
item.client_id == client.client_id
}) {
//Find the item in the tableArray by the client id and update it there too
// I am writing an example code here, this is not tested so just get the logic from here.
//if let index = self.tableArray.index(where: { (item) -> Bool in
// item.id == client.id
//}) {
self.tableArray[index] = client
//self.tableArray.replace(client, at: index)
//}
print("update")
print(tableArray)
}
else {
// Add a client.
tableArray.append(client)
print("add")
}
}
// Now update the sections Array and it will have all the correct values
self.prepareData()
DispatchQueue.main.async {
self.tableView.reloadData()
}
// if(wasDeleted) {
// if let selectedIndexPath = tableView.indexPathForSelectedRow {
// print("Delteted")
// sections[selectedIndexPath.section].remove(at: selectedIndexPath.row)
// }
//
// }
// else {
// if let selectedIndexPath = tableView.indexPathForSelectedRow {
// // Update an existing client.
// sections[selectedIndexPath.section][selectedIndexPath.row] = client
// //tableView.reloadRows(at: [selectedIndexPath], with: .automatic)
// print("update")
// print(tableArray)
// }
// else {
// // Add a client.
// tableArray.append(client)
// print("add")
// self.prepareData()
// }
// }
//
// DispatchQueue.main.async {
//
// self.tableView.reloadData()
// }
// if(wasDeleted) {
// if let selectedIndexPath = tableView.indexPathForSelectedRow {
// print("Delteted")
// tableArray.remove(at: selectedIndexPath.row)
//// DispatchQueue.main.async {
//// // Deleting the row in the tableView
//// if self.tableView.numberOfRows(inSection: selectedIndexPath.section) > 1 {
//// self.tableView.deleteRows(at: [selectedIndexPath], with: UITableViewRowAnimation.bottom)
//// } else {
//// let indexSet = NSMutableIndexSet()
//// indexSet.add(selectedIndexPath.section)
//// self.tableView.deleteSections(indexSet as IndexSet, with: UITableViewRowAnimation.bottom)
//// }
////
//// }
// }
//
// }
// else {
// if let selectedIndexPath = tableView.indexPathForSelectedRow {
// // Update an existing client.
// tableArray[selectedIndexPath.row] = client
// //tableView.reloadRows(at: [selectedIndexPath], with: .automatic)
// print("update")
// print(tableArray)
// }
// else {
// // Add a client.
// tableArray.append(client)
// print("add")
// }
// }
// self.prepareData()
// DispatchQueue.main.async {
//
// self.tableView.reloadData()
// }
}
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
let secondScene = segue.destination as! ClientViewController
if segue.identifier == "ShowDetail", let indexPath = self.tableView.indexPathForSelectedRow {
let currentPhoto = sections[indexPath.section][indexPath.row]
secondScene.client = currentPhoto
}
else if segue.identifier == "AddItem" {
print("add")
}
else {
fatalError("The selected cell is not being displayed by the table")
}
}
#objc func handleRefresh(_ refreshControl: UIRefreshControl) {
getClients()
}
}
extension ClientsViewController {
override func viewDidLoad() {
super.viewDidLoad()
self.refreshControl?.addTarget(self, action: #selector(ClientsViewController.handleRefresh(_:)), for: UIControlEvents.valueChanged)
tableView.backgroundView = nil
noClientsLabel.text = ""
getClients() //for only the 1st time ==> when view is created ==> ok ish
}
override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
if(self.tableArray.count > 0) {
return sortedFirstLetters[section]
}
else {
return ""
}
}
override func sectionIndexTitles(for tableView: UITableView) -> [String]? {
return sortedFirstLetters
}
override func numberOfSections(in tableView: UITableView) -> Int {
return sections.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let item = sections[indexPath.section][indexPath.row]
let cell = tableView.dequeueReusableCell(withIdentifier: "ClientCell", for: indexPath)
cell.textLabel?.text = item.name
cell.detailTextLabel?.text = item.city + " - " + item.province
return cell
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return sections[section].count
}
func getClients() {
print("called server")
self.refreshControl?.beginRefreshing()
self.tableView.setContentOffset(CGPoint(x:0, y:-100), animated: true)
makeRequest(endpoint: "api/clients/all",
parameters: [:],
completionHandler: { (container : ApiContainer<Client>?, error : Error?) in
if let error = error {
print("error calling POST on /getClients")
print(error)
return
}
self.tableArray = (container?.result)!
self.prepareData()
DispatchQueue.main.async {
if(self.tableArray.isEmpty)
{
self.noClientsLabel.text = "bNo Clients"
self.tableView.backgroundView?.isHidden = false
self.noClientsLabel.text = ""
print("all")
}
else{
print("nothing")
}
self.tableView.reloadData()
self.refreshControl?.endRefreshing()
}
} )
}
//sorts and makes the index
func prepareData() {
let firstLetters = self.tableArray.map { $0.nameFirstLetter }
let uniqueFirstLetters = Array(Set(firstLetters))
self.sortedFirstLetters = uniqueFirstLetters.sorted()
self.sections = self.sortedFirstLetters.map { firstLetter in
return self.tableArray
.filter { $0.nameFirstLetter == firstLetter }
.sorted { $0.name < $1.name }
}
}
}
You are editing the wrong datasource. You should edit or update the sections array not tableArray.
Change your code in unwindToClients here :
if(wasDeleted) {
if let selectedIndexPath = tableView.indexPathForSelectedRow {
print("Delteted")
tableArray.remove(at: selectedIndexPath.row)
}
}
else {
if let selectedIndexPath = tableView.indexPathForSelectedRow {
// Update an existing client.
tableArray[selectedIndexPath.row] = client
//tableView.reloadRows(at: [selectedIndexPath], with: .automatic)
print("update")
print(tableArray)
}
else {
// Add a client.
tableArray.append(client)
print("add")
}
}
self.prepareData()
DispatchQueue.main.async {
self.tableView.reloadData()
}
with this :
if(wasDeleted) {
if let selectedIndexPath = tableView.indexPathForSelectedRow {
print("Delteted")
sections[selectedIndexPath.section].remove(at: selectedIndexPath.row)
}
}
else {
if let selectedIndexPath = tableView.indexPathForSelectedRow {
// Update an existing client.
sections[selectedIndexPath.section][selectedIndexPath.row] = client
//tableView.reloadRows(at: [selectedIndexPath], with: .automatic)
print("update")
print(tableArray)
}
else {
// Add a client.
tableArray.append(client)
print("add")
self.prepareData()
}
}
DispatchQueue.main.async {
self.tableView.reloadData()
}
To fix the incorrect section headers, try doing something like this:
if(wasDeleted) {
if let index = self.tableArray.index(where: { (item) -> Bool in
item.id == client.id
}) {
print("Delteted")
// Find the client in the tableArray by the client id and remove it from the tableArray
// I am writing an example code here, this is not tested so just get the logic from here.
//self.tableArray.remove(at: index)
}
}
else {
if self.tableArray.contains(client) {
//Find the item in the tableArray by the client id and update it there too
// I am writing an example code here, this is not tested so just get the logic from here.
//if let index = self.tableArray.index(where: { (item) -> Bool in
// item.id == client.id
//}) {
// self.tableArray.replace(client, at: index)
//}
print("update")
print(tableArray)
}
else {
// Add a client.
tableArray.append(client)
print("add")
}
}
// Now update the sections Array and it will have all the correct values
self.prepareData()
DispatchQueue.main.async {
self.tableView.reloadData()
}
I've autogenerated an application from the SAP Cloud SDK Assistant, and I'd like to use a FUIValuePickerFormCell in the detail view of the application, but can't seem to do so.
I've used the sample codes given by the SAP Fiori mentor app, and added a Table View Cell of class "FUIValuePickerFormCell" in main.storyboard, but nothing happens when the cell is tapped, the pickerview doesn't come up, nor is the cell editable. Does anyone knows why is this so? Below are the codes that I used
Cell that i want to change in ProductsTypeDetailTableDelegate
case 6:
let cell = tableView.dequeueReusableCell(withIdentifier: FUIValuePickerFormCell.reuseIdentifier, for: indexPath) as! FUIValuePickerFormCell
valuePickerCell = cell
cell.isEditable = true
cell.keyName = "Appointment Status"
cell.valueOptions = ["1", "2", "3"]
cell.value = 1 //index of first value
cell.onChangeHandler = { newValue in
if let option = self.valuePickerCell?.valueOptions[newValue]{
print("Selected value option \(option)")
}
}
return cell
DetailViewController:
import SAPFoundation
import SAPOData
import SAPFiori
import SAPCommon
class DetailViewController: FUIFormTableViewController, Notifier, LoadingIndicator {
private let appDelegate = UIApplication.shared.delegate as! AppDelegate
private var tableDelegate: DetailTableDelegate!
var tableUpdater: TableUpdaterDelegate?
var loadingIndicator: FUILoadingIndicatorView?
private let logger = Logger.shared(named: "DetailViewControllerLogger")
var services: ServicesDataAccess {
return appDelegate.services
}
// The Entity which will be edited on the Detail View
var selectedEntity: EntityValue!
var entityArray: [EntityValue]!
var entityArray2: [EntityValue]!
var entityArray3: [EntityValue]!
var prodimages: [EntityValue]!
var collectionType: CollectionType = .none {
didSet {
if let delegate = self.generatedTableDelegate() {
self.tableDelegate = delegate
if self.selectedEntity != nil {
self.tableDelegate.entity = self.selectedEntity
}
if self.entityArray != nil {
self.tableDelegate.arrayEntity = self.entityArray
}
if self.entityArray2 != nil {
self.tableDelegate.arrayEntity2 = self.entityArray2
}
if self.entityArray3 != nil {
self.tableDelegate.arrayEntity3 = self.entityArray3
}
if self.prodimages != nil{
self.tableDelegate.prodimages = self.prodimages
}
}
}
}
override func viewDidLoad() {
super.viewDidLoad()
self.tableView.allowsSelection = false
self.tableView.dataSource = tableDelegate
self.tableView.delegate = tableDelegate
self.tableView.rowHeight = UITableViewAutomaticDimension
self.tableView.estimatedRowHeight = 44
}
#IBAction func updateEntity(_ sender: AnyObject) {
self.showIndicator()
self.view.endEditing(true)
self.logger.info("Updating entity in backend.")
self.services.service.updateEntity(self.tableDelegate.entity) { error in
self.hideIndicator()
if let error = error {
self.logger.error("Update entry failed.", error: error)
self.displayAlert(title: NSLocalizedString("keyErrorEntityUpdateTitle", value: "Update entry failed", comment: "XTIT: Title of alert message about entity update failure."),
message: NSLocalizedString("keyErrorEntityUpdateBody", value: error.localizedDescription, comment: "XMSG: Body of alert message about entity update failure."))
return
}
self.logger.info("Update entry finished successfully.")
FUIToastMessage.show(message: NSLocalizedString("keyUpdateEntityFinishedTitle", value: "Updated", comment: "XTIT: Title of alert message about successful entity update."))
self.tableUpdater?.updateTable()
}
}
func createEntity() {
self.showIndicator()
self.view.endEditing(true)
self.logger.info("Creating entity in backend.")
self.services.service.createEntity(self.tableDelegate.entity) { error in
self.hideIndicator()
if let error = error {
self.logger.error("Create entry failed.", error: error)
self.displayAlert(title: NSLocalizedString("keyErrorEntityCreationTitle", value: "Create entry failed", comment: "XTIT: Title of alert message about entity creation error."),
message: NSLocalizedString("keyErrorEntityCreationBody", value: error.localizedDescription, comment: "XMSG: Body of alert message about entity creation error."))
return
}
self.logger.info("Create entry finished successfully.")
DispatchQueue.main.async {
self.dismiss(animated: true) {
FUIToastMessage.show(message: NSLocalizedString("keyEntityCreationBody", value: "Created", comment: "XMSG: Title of alert message about successful entity creation."))
self.tableUpdater?.updateTable()
}
}
}
}
func cancel() -> Void {
DispatchQueue.main.async {
self.dismiss(animated: true, completion: nil)
}
}
// Test code
private func updateTable(completionHandler: #escaping() -> Void) {
self.tableDelegate?.requestEntities { error in
defer {
completionHandler()
}
if let error = error {
self.displayAlert(title: NSLocalizedString("keyErrorLoadingData", value: "Loading data failed!", comment: "XTIT: Title of loading data error pop up."),
message: error.localizedDescription)
self.logger.error("Could not update table.", error: error)
return
}
DispatchQueue.main.async {
self.tableView.reloadData()
self.logger.info("Table updated successfully!")
}
}
}
private func configureView() {
if self.collectionType != .none {
self.title = collectionType.rawValue
if let tableDelegate = self.generatedTableDelegate() {
self.tableDelegate = tableDelegate
if let tableView = self.tableView {
tableView.delegate = tableDelegate
tableView.dataSource = tableDelegate
self.updateTable()
}
}
}
}
func updateTable() {
self.showIndicator()
DispatchQueue.global().async {
self.updateTable() {
self.hideIndicator()
}
}
}
// test code ends
}
DetailTableDelegate:
import SAPOData
import SAPFiori
import SAPFoundation
protocol DetailTableDelegate: UITableViewDelegate, UITableViewDataSource {
var entity: EntityValue { get set }
var arrayEntity: [EntityValue] { get set }
var arrayEntity2: [EntityValue] { get set }
var arrayEntity3: [EntityValue] { get set }
var prodimages: [EntityValue] { get set}
}
extension DetailTableDelegate {
}
extension DetailViewController {
func generatedTableDelegate() -> DetailTableDelegate? {
switch self.collectionType {
case .customers:
return CUSTOMERSTypeDetailTableDelegate(dataAccess: self.services, rightBarButton: self.navigationItem.rightBarButtonItem!)
case .suppliers:
return SUPPLIERSTypeDetailTableDelegate(dataAccess: self.services, rightBarButton: self.navigationItem.rightBarButtonItem!)
case .orders:
return ORDERSTypeDetailTableDelegate(dataAccess: self.services, rightBarButton: self.navigationItem.rightBarButtonItem!, count: Int())
case .products:
return PRODUCTSTypeDetailTableDelegate(dataAccess: self.services, rightBarButton: self.navigationItem.rightBarButtonItem!)
default:
return nil
}
}
}
ProductsTypeDetailTableDelegate:
import Foundation
import UIKit
import SAPOData
import SAPCommon
import SAPFiori
class PRODUCTSTypeDetailTableDelegate: NSObject, DetailTableDelegate {
private let dataAccess: ServicesDataAccess
private var _entity: PRODUCTSType?
// test code
private var _arrayEntity: [PRODUCTSType] = [PRODUCTSType]()
private var _arrayEntity2: [PRODUCTSType] = [PRODUCTSType]()
private var _arrayEntity3: [PRODUCTSType] = [PRODUCTSType]()
private var _prodimages: [PRODIMGType] = [PRODIMGType]()
var valuePickerCell: FUIValuePickerFormCell?
var prodimages: [EntityValue] {
get {
return _prodimages
}
set {
self._prodimages = newValue as! [PRODIMGType]
}
}
var arrayEntity: [EntityValue] {
get {
return _arrayEntity
}
set {
self._arrayEntity = newValue as! [PRODUCTSType]
}
}
var arrayEntity2: [EntityValue] {
get {
return _arrayEntity2
}
set {
self._arrayEntity2 = newValue as! [PRODUCTSType]
}
}
var arrayEntity3: [EntityValue] {
get {
return _arrayEntity3
}
set {
self._arrayEntity3 = newValue as! [PRODUCTSType]
}
}
// test code ends
var entity: EntityValue {
get {
if _entity == nil {
_entity = createEntityWithDefaultValues()
}
return _entity!
}
set {
_entity = newValue as? PRODUCTSType
}
}
var rightBarButton: UIBarButtonItem
private var validity = Array(repeating: true, count: 8)
init(dataAccess: ServicesDataAccess, rightBarButton: UIBarButtonItem) {
self.dataAccess = dataAccess
self.rightBarButton = rightBarButton
self.rightBarButton.isEnabled = false
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
guard let currentEntity = self.entity as? PRODUCTSType else {
return cellForDefault(tableView: tableView, indexPath: indexPath)
}
switch indexPath.row {
case 0:
var value = ""
let name = "Product ID"
if currentEntity.hasDataValue(for: PRODUCTSType.prodid) {
value = "\(currentEntity.prodid)"
}
return cellForProperty(tableView: tableView, indexPath: indexPath, property: PRODUCTSType.prodid, value: value, name: name, changeHandler: { (newValue: String) -> Bool in
if let validValue = TypeValidator.validInteger(from: newValue) {
currentEntity.prodid = validValue
self.validity[0] = true
} else {
self.validity[0] = false
}
self.barButtonShouldBeEnabled()
return self.validity[0]
})
case 1:
var value = ""
let name = "Name"
if currentEntity.hasDataValue(for: PRODUCTSType.prodname) {
if let prodname = currentEntity.prodname {
value = "\(prodname)"
}
}
return cellForProperty(tableView: tableView, indexPath: indexPath, property: PRODUCTSType.prodname, value: value, name: name, changeHandler: { (newValue: String) -> Bool in
// The property is optional, so nil value can be accepted
if newValue.isEmpty {
currentEntity.prodname = nil
self.validity[1] = false
} else {
if let validValue = TypeValidator.validString(from: newValue, for: PRODUCTSType.prodname) {
currentEntity.prodname = validValue
self.validity[1] = true
} else {
self.validity[1] = false
}
}
self.barButtonShouldBeEnabled()
return self.validity[1]
})
case 2:
var value = ""
let name = "Description"
if currentEntity.hasDataValue(for: PRODUCTSType.proddesc) {
if let proddesc = currentEntity.proddesc {
value = "\(proddesc)"
}
}
return cellForProperty(tableView: tableView, indexPath: indexPath, property: PRODUCTSType.proddesc, value: value, name: name, changeHandler: { (newValue: String) -> Bool in
// The property is optional, so nil value can be accepted
if newValue.isEmpty {
currentEntity.proddesc = nil
self.validity[2] = false
} else {
if let validValue = TypeValidator.validString(from: newValue, for: PRODUCTSType.proddesc) {
currentEntity.proddesc = validValue
self.validity[2] = true
} else {
self.validity[2] = false
}
}
self.barButtonShouldBeEnabled()
return self.validity[2]
})
case 3:
var value = ""
let name = "Current Stock"
if currentEntity.hasDataValue(for: PRODUCTSType.currstock) {
if let currstock = currentEntity.currstock {
value = "\(currstock)"
}
}
return cellForProperty(tableView: tableView, indexPath: indexPath, property: PRODUCTSType.currstock, value: value, name: name, changeHandler: { (newValue: String) -> Bool in
// The property is optional, so nil value can be accepted
if newValue.isEmpty {
currentEntity.currstock = 0
self.validity[3] = true
} else {
if let validValue = TypeValidator.validInteger(from: newValue) {
currentEntity.currstock = validValue
self.validity[3] = true
} else {
self.validity[3] = false
}
}
self.barButtonShouldBeEnabled()
return self.validity[3]
})
case 4:
var value = ""
let name = "Minimum Stock"
if currentEntity.hasDataValue(for: PRODUCTSType.minstock) {
if let minstock = currentEntity.minstock {
value = "\(minstock)"
}
}
return cellForProperty(tableView: tableView, indexPath: indexPath, property: PRODUCTSType.minstock, value: value, name: name, changeHandler: { (newValue: String) -> Bool in
// The property is optional, so nil value can be accepted
if newValue.isEmpty {
currentEntity.minstock = 0
self.validity[4] = true
} else {
if let validValue = TypeValidator.validInteger(from: newValue) {
currentEntity.minstock = validValue
self.validity[4] = true
} else {
self.validity[4] = false
}
}
self.barButtonShouldBeEnabled()
return self.validity[4]
})
case 5:
var value = ""
let name = "Price"
if currentEntity.hasDataValue(for: PRODUCTSType.price) {
if let price = currentEntity.price {
value = "\(price)"
}
}
return cellForProperty(tableView: tableView, indexPath: indexPath, property: PRODUCTSType.price, value: value, name: name, changeHandler: { (newValue: String) -> Bool in
// The property is optional, so nil value can be accepted
if newValue.isEmpty {
currentEntity.price = nil
self.validity[5] = false
} else {
if let validValue = TypeValidator.validBigDecimal(from: newValue) {
currentEntity.price = validValue
self.validity[5] = true
} else {
self.validity[5] = false
}
}
self.barButtonShouldBeEnabled()
return self.validity[5]
})
case 6:
// var value = ""
// let name = "Category"
// if currentEntity.hasDataValue(for: PRODUCTSType.cat) {
// if let cat = currentEntity.cat {
// value = "\(cat)"
// }
// }
// return cellForProperty(tableView: tableView, indexPath: indexPath, property: PRODUCTSType.cat, value: value, name: name, changeHandler: { (newValue: String) -> Bool in
// // The property is optional, so nil value can be accepted
// if newValue.isEmpty {
// currentEntity.cat = nil
// self.validity[6] = false
// } else {
// if let validValue = TypeValidator.validString(from: newValue, for: PRODUCTSType.cat) {
// currentEntity.cat = validValue
// self.validity[6] = true
// } else {
// self.validity[6] = false
// }
// }
// self.barButtonShouldBeEnabled()
// return self.validity[6]
// })
let cell = tableView.dequeueReusableCell(withIdentifier: FUIValuePickerFormCell.reuseIdentifier, for: indexPath) as! FUIValuePickerFormCell
valuePickerCell = cell
cell.isEditable = true
cell.keyName = "Appointment Status"
cell.valueOptions = ["1", "2", "3"]
cell.value = 1 //index of first value
cell.onChangeHandler = { newValue in
if let option = self.valuePickerCell?.valueOptions[newValue]{
print("Selected value option \(option)")
}
}
return cell
case 7:
var value = ""
let name = "Supplier ID"
if currentEntity.hasDataValue(for: PRODUCTSType.suppid) {
if let suppid = currentEntity.suppid {
value = "\(suppid)"
}
}
return cellForProperty(tableView: tableView, indexPath: indexPath, property: PRODUCTSType.suppid, value: value, name: name, changeHandler: { (newValue: String) -> Bool in
// The property is optional, so nil value can be accepted
if newValue.isEmpty {
currentEntity.suppid = nil
self.validity[7] = true
} else {
if let validValue = TypeValidator.validInteger(from: newValue) {
currentEntity.suppid = validValue
self.validity[7] = true
} else {
self.validity[7] = false
}
}
self.barButtonShouldBeEnabled()
return self.validity[7]
})
default:
return cellForDefault(tableView: tableView, indexPath: indexPath)
}
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 8
}
func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
return true
}
func createEntityWithDefaultValues() -> PRODUCTSType {
let newEntity = PRODUCTSType()
newEntity.prodid = self._arrayEntity.count + 1
return newEntity
}
// Check if all text fields are valid
private func barButtonShouldBeEnabled() {
let anyFieldInvalid = self.validity.first { (field) -> Bool in
return field == false
}
self.rightBarButton.isEnabled = anyFieldInvalid == nil
}
func cellForProperty(tableView: UITableView, indexPath: IndexPath, property: Property, value: String, name: String, changeHandler: #escaping((String) -> Bool)) -> UITableViewCell {
let cell: UITableViewCell!
if property.dataType.isBasic {
// The property is a key or we are creating new entity
if (!property.isKey || self.entity.isNew) {
// .. that CAN be edited
cell = self.cellWithEditableContent(tableView: tableView, indexPath: indexPath, property: property, with: value, with: name, changeHandler: changeHandler)
} else {
// .. that CANNOT be edited
cell = self.cellWithNonEditableContent(tableView: tableView, indexPath: indexPath, for: property.name, with: value, with: name)
}
} else {
// A complex property
cell = self.cellWithNonEditableContent(tableView: tableView, indexPath: indexPath, for: property.name, with: "...", with: name)
}
return cell
}
func cellForDefault(tableView: UITableView, indexPath: IndexPath) -> FUISimplePropertyFormCell {
let cell = tableView.dequeueReusableCell(withIdentifier: FUISimplePropertyFormCell.reuseIdentifier, for: indexPath) as! FUISimplePropertyFormCell
cell.textLabel!.text = ""
cell.textLabel!.numberOfLines = 0
cell.textLabel!.lineBreakMode = NSLineBreakMode.byWordWrapping
cell.keyName = "default"
return cell
}
private func cellWithEditableContent(tableView: UITableView, indexPath: IndexPath, property: Property, with value: String, with name: String, changeHandler: #escaping((String) -> Bool)) -> FUISimplePropertyFormCell {
let cell = tableView.dequeueReusableCell(withIdentifier: FUISimplePropertyFormCell.reuseIdentifier, for: indexPath) as! FUISimplePropertyFormCell
cell.isEditable = true
cell.keyName = name
cell.value = value
if !property.isOptional {
cell.valueTextField!.placeholder = NSLocalizedString("keyRequiredPlaceholder", value: "Required", comment: "XSEL: Placeholder text for required but currently empty textfield.")
}
cell.onChangeHandler = { (newValue) -> Void in
if !changeHandler(newValue) {
cell.valueTextField.textColor = UIColor.red
} else {
cell.valueTextField.textColor = UIColor.gray
}
}
return cell
}
private func cellWithNonEditableContent(tableView: UITableView, indexPath: IndexPath, for key: String, with value: String, with name: String) -> FUISimplePropertyFormCell {
let cell = tableView.dequeueReusableCell(withIdentifier: FUISimplePropertyFormCell.reuseIdentifier, for: indexPath) as! FUISimplePropertyFormCell
cell.keyName = name
cell.value = value
return cell
}
private func selectKeyboardFor(_ type: DataType) -> UIKeyboardType {
switch type.code {
case DataType.byte, DataType.short, DataType.integer, DataType.int:
return .decimalPad
case DataType.decimal, DataType.double, DataType.localDateTime, DataType.globalDateTime:
return .numbersAndPunctuation
default:
return .`default`
}
}
func defaultValueFor(_ property: Property) -> Double {
if let defaultValue = property.defaultValue {
return Double(defaultValue.toString())!
} else {
return Double()
}
}
func defaultValueFor(_ property: Property) -> BigDecimal {
if let defaultValue = property.defaultValue {
return (defaultValue as! DecimalValue).value
} else {
return BigDecimal.fromDouble(Double())
}
}
func defaultValueFor(_ property: Property) -> Int {
if let defaultValue = property.defaultValue {
return Int(defaultValue.toString())!
} else {
return Int()
}
}
func defaultValueFor(_ property: Property) -> BigInteger {
if let defaultValue = property.defaultValue {
return BigInteger(defaultValue.toString())
} else {
return BigInteger.fromInt(Int())
}
}
func defaultValueFor(_ property: Property) -> Int64 {
if let defaultValue = property.defaultValue {
return Int64(defaultValue.toString())!
} else {
return Int64()
}
}
func defaultValueFor(_ property: Property) -> Float {
if let defaultValue = property.defaultValue {
return Float(defaultValue.toString())!
} else {
return Float()
}
}
func defaultValueFor(_ property: Property) -> LocalDateTime {
if let defaultValue = property.defaultValue {
return LocalDateTime.parse(defaultValue.toString())!
} else {
return LocalDateTime.now()
}
}
func defaultValueFor(_ property: Property) -> GlobalDateTime {
if let defaultValue = property.defaultValue {
return GlobalDateTime.parse(defaultValue.toString())!
} else {
return GlobalDateTime.now()
}
}
func defaultValueFor(_ property: Property) -> GuidValue {
if let defaultValue = property.defaultValue {
return GuidValue.parse(defaultValue.toString())!
} else {
return GuidValue.random()
}
}
func defaultValueFor(_ property: Property) -> String {
if let defaultValue = property.defaultValue {
return defaultValue.toString()
} else {
return ""
}
}
func defaultValueFor(_ property: Property) -> Bool {
if let defaultValue = property.defaultValue {
return defaultValue.toString().toBool()!
} else {
return Bool()
}
}
}
From your description, I assume you are using a UITableViewController and not the FUIFormTableViewController. The events of “FUI*FormCells” are handled only by the FUIFormTableViewController, not by a UITableViewController.
I have a table view with two different prototype cells.
The second prototype cell has a custom Label, but when I execute the project it's showing nothing. The text is there (I know because it's printing) but it's not appearing.
TableView Storyboard
Simulator: Image cell ok, but text cell is empty
-> TableViewController:
import UIKit
import Twitter
class TweetMentionsTableViewController: UITableViewController
{
lazy var images: [MediaItem] = []
lazy var userMentions: [Mention]? = []
lazy var hashtags: [Mention]? = []
lazy var urls: [Mention]? = []
var tweet: Twitter.Tweet?
private enum MentionTypes {
case Images
case Hashtags
case Users
case URLs
}
private var mentionsCollection: Dictionary<MentionTypes, Bool> = [
MentionTypes.Images: false,
MentionTypes.Hashtags: false,
MentionTypes.Users: false,
MentionTypes.URLs: false
]
private var sectionTypes: Dictionary<MentionTypes, Int?> = [
MentionTypes.Images: nil,
MentionTypes.Hashtags: nil,
MentionTypes.Users: nil,
MentionTypes.URLs: nil
]
override func numberOfSections(in tableView: UITableView) -> Int {
var count = 0
if !(tweet?.media.isEmpty)! {
mentionsCollection[MentionTypes.Images] = true
count += 1
}
if !(tweet?.hashtags.isEmpty)! {
mentionsCollection[MentionTypes.Hashtags] = true
count += 1
}
if !(tweet?.userMentions.isEmpty)! {
mentionsCollection[MentionTypes.Users] = true
count += 1
}
if !(tweet?.urls.isEmpty)! {
mentionsCollection[MentionTypes.URLs] = true
count += 1
}
return count
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if mentionsCollection[MentionTypes.Images] == true {
sectionTypes[MentionTypes.Images] = section
mentionsCollection[MentionTypes.Images] = false
return (tweet?.media.count)!
} else if mentionsCollection[MentionTypes.Hashtags] == true {
sectionTypes[MentionTypes.Hashtags] = section
mentionsCollection[MentionTypes.Hashtags] = false
return (tweet?.hashtags.count)!
} else if mentionsCollection[MentionTypes.Users] == true {
sectionTypes[MentionTypes.Users] = section
mentionsCollection[MentionTypes.Users] = false
return (tweet?.userMentions.count)!
} else if mentionsCollection[MentionTypes.URLs] == true {
sectionTypes[MentionTypes.URLs] = section
mentionsCollection[MentionTypes.URLs] = false
return (tweet?.urls.count)!
}
return 0
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
//let data = temp[indexPath.row][indexPath.section]
let cell = tableView.dequeueReusableCell(withIdentifier: "TweetMention", for: indexPath)
// Configure the cell...
if let sec = sectionTypes[MentionTypes.Images], indexPath.section == sec {
let image = tweet?.media[indexPath.row].url
if let tweetMentionCell = cell as? TweetMentionsTableViewCell {
tweetMentionCell.imageURL = image!
return cell
}
}
let cell2 = tableView.dequeueReusableCell(withIdentifier: "TweetMention2Cell", for: indexPath)
if let sec = sectionTypes[MentionTypes.Hashtags], indexPath.section == sec {
let hashtag = tweet?.hashtags[indexPath.row]
if let tweetMentionCell = cell2 as? TweetMentions2TableViewCell {
tweetMentionCell.hashtag = (hashtag?.keyword)!
}
} else if let sec = sectionTypes[MentionTypes.Users], indexPath.section == sec {
let userMention = tweet?.userMentions[indexPath.row]
if let tweetMentionCell = cell2 as? TweetMentions2TableViewCell {
tweetMentionCell.userMention = (userMention?.keyword)!
}
} else if let sec = sectionTypes[MentionTypes.URLs], indexPath.section == sec {
let url = tweet?.urls[indexPath.row]
if let tweetMentionCell = cell2 as? TweetMentions2TableViewCell {
tweetMentionCell.url = (url?.keyword)!
}
}
return cell2
}
override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
if let sec = sectionTypes[MentionTypes.Images], section == sec {
return "Images"
} else if let sec = sectionTypes[MentionTypes.Hashtags], section == sec {
return "Hashtags"
} else if let sec = sectionTypes[MentionTypes.Users], section == sec {
return "Users"
} else if let sec = sectionTypes[MentionTypes.URLs], section == sec {
return "URLs"
}
return nil
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if let cell = sender as? TweetMentionsTableViewCell {
if segue.identifier == "Show Image" {
if let imageVC = segue.destination as? ImageViewController {
imageVC.imageURL = cell.imageURL?.absoluteURL
//imageVC.imageRatio = tweet?.media[0].aspectRatio
}
}
}
if let cell = sender as? TweetMentions2TableViewCell {
if segue.identifier == "Show Text" {
if let mentionsSTTVC = segue.destination as? MentionsSearchTweetTableViewController {
if let text = cell.mentLabel {
mentionsSTTVC.mentionToSearch = text.text!
}
}
}
}
}
override func shouldPerformSegue(withIdentifier identifier: String, sender: Any?) -> Bool {
if let cell = sender as? TweetMentions2TableViewCell {
if (cell.url.contains("http")) {
UIApplication.shared.open(NSURL(string: cell.url)! as URL)
return false
}
}
return true
}
}
-> TableViewCell:
import UIKit
class TweetMentions2TableViewCell: UITableViewCell
{
#IBOutlet weak var mentLabel: UILabel!
var userMention = "" {
didSet {
updateUI(mentionType: 2)
}
}
var hashtag = "" {
didSet {
updateUI(mentionType: 1)
}
}
var url = "" {
didSet {
updateUI(mentionType: 3)
}
}
func updateUI(mentionType: Int) {
if mentionType == 1 {
mentLabel.text = hashtag
} else if mentionType == 2 {
mentLabel.text = userMention
} else if mentionType == 3 {
mentLabel.text = url
}
print(mentLabel.text!)
}
}
So my table view is not loading anything and I think it's because of this warning that I get. It saids the save function is not being used so how can it load something that is not saved. What I am saving is the indexPath and Section of the row that the user selected via a button action in the row.
Warning:
Result of call to 'save(defaults:)' is unused
Code:
func saveSorting(_ dataIdBlock: (Any) -> String) {
guard let items = self.items else { return }
for (section, rows) in items.enumerated() {
for (row, item) in rows.enumerated() {
let indexPath = IndexPath(row: row, section: section)
let dataId = dataIdBlock(item)
let ordering = DataHandling(dataId: dataId, indexPath: indexPath)
// Warning is here
ordering.save(defaults: indexPath.defaultsKey)
}
}
}
}
NSCoder Class for DataHandling / ordering.save
DataHandling.swift
class DataHandling: NSObject, NSCoding {
var indexPath: IndexPath?
var dataId: String?
init(dataId: String, indexPath: IndexPath) {
super.init()
self.dataId = dataId
self.indexPath = indexPath
}
required init(coder aDecoder: NSCoder) {
if let dataId = aDecoder.decodeObject(forKey: "dataId") as? String {
self.dataId = dataId
}
if let indexPath = aDecoder.decodeObject(forKey: "indexPath") as? IndexPath {
self.indexPath = indexPath
}
}
func encode(with aCoder: NSCoder) {
aCoder.encode(dataId, forKey: "dataId")
aCoder.encode(indexPath, forKey: "indexPath")
}
func save(defaults box: String) -> Bool {
let defaults = UserDefaults.standard
let savedData = NSKeyedArchiver.archivedData(withRootObject: self)
defaults.set(savedData, forKey: box)
return defaults.synchronize()
}
convenience init?(defaults box: String) {
let defaults = UserDefaults.standard
if let data = defaults.object(forKey: box) as? Data,
let obj = NSKeyedUnarchiver.unarchiveObject(with: data) as? DataHandling,
let dataId = obj.dataId,
let indexPath = obj.indexPath {
self.init(dataId: dataId, indexPath: indexPath)
} else {
return nil
}
}
class func allSavedOrdering(_ maxRows: Int) -> [Int: [DataHandling]] {
var result: [Int: [DataHandling]] = [:]
for section in 0...1 {
var rows: [DataHandling] = []
for row in 0..<maxRows {
let indexPath = IndexPath(row: row, section: section)
if let ordering = DataHandling(defaults: indexPath.defaultsKey) {
rows.append(ordering)
}
rows.sort(by: { $0.indexPath! < $1.indexPath! })
}
result[section] = rows
}
return result
}
}
Other code I'm using:
// Number of Rows in Section
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.items?[section].count ?? 0
}
// Number of Sections
func numberOfSections(in tableView: UITableView) -> Int {
return self.items?.count ?? 0
}
Saving it with:
saveSorting() { "\($0)" }
Loading it in ViewDidLoad:
func fetchData() {
// Load Data from Server to testArray
retrieveData()
// request from remote or local
data = [testArray]
// Update the items to first section has 0 elements,
// and place all data in section 1
items = [[], data ?? []]
// apply ordering
applySorting() { "\($0)" }
// save ordering
saveSorting() { "\($0)" }
// refresh the table view
myTableView.reloadData()
}
Loading Code:
// Loading
func applySorting(_ dataIdBlock: (Any) -> String) {
// get all saved ordering
guard let data = self.data else { return }
let ordering = DataHandling.allSavedOrdering(data.count)
var result: [[Any]] = [[], []]
for (section, ordering) in ordering {
guard section <= 1 else { continue } // make sure the section is 0 or 1
let rows = data.filter({ obj -> Bool in
return ordering.index(where: { $0.dataId == .some(dataIdBlock(obj)) }) != nil
})
result[section] = rows
}
self.items = result
}
The DataHandling instance's save(defaults:) function technically returns a value, even if you don't use it. To silence this warning, assign it to _ to signify that you don't intend to use the result value, e.g.:
_ = ordering.save(defaults: indexPath.defaultsKey)
or
let _ = ordering.save(defaults: indexPath.defaultsKey)
Just to be clear, this is almost definitely not why your tableview is not loading data. It should be pretty insignificant. The indexPath.defaultsKey is being saved (assuming the API works).