How to make the UILabel replace the NavigationBar large title? - ios

I am a beginner to Xcode and Swift and I am currently creating an application where the user adds a person on the application and after that it right the amount of money they owe that person or that person owes him/her.
I actually want to show the user their current balance with other user on NavigationBar Large title and currently I am doing that by using frame where I define the width, height and x,y positions of frame that is replaced by UILabel. However, I wish the balance to be replaced on the NavigationBar Large Title. I am trying to find a solution to this from past 3 days therefore can you please help me? Thanks a lot in advance
import UIKit
class PersonDetailTableViewController: UITableViewController {
let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
var person: People?
var owe: Owe?
#IBOutlet var personTable: UITableView!
var dataInfo: [Owe] = []
var selectedObject: [Owe] = []
var balanceAmount = "Balance: "
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return (dataInfo.count)
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = personTable
.dequeueReusableCell(withIdentifier: "detailsCell", for: indexPath)
cell.textLabel?.text = dataInfo[indexPath.row].name
cell.detailTextLabel?.text = "₹ \(dataInfo[indexPath.row].amount)"
if dataInfo[indexPath.row].amount < 0 {
cell.detailTextLabel?.textColor = UIColor.red
} else {
cell.detailTextLabel?.textColor = UIColor.green
}
return cell
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
selectedObject = [dataInfo[indexPath.row]]
performSegue(withIdentifier: "addOweDetails", sender: nil)
tableView.deselectRow(at: indexPath, animated: true)
}
override func viewDidLoad() {
super.viewDidLoad()
getData()
personTable.dataSource = self
addTotalToNav()
print(dataInfo as Any)
}
// MARK: - Table view data source
func addTotalToNav() -> Void {
if let navigationBar = self.navigationController?.navigationBar {
let totalFrame = CGRect(x: 20, y: 0, width: navigationBar.frame.width/2, height: navigationBar.frame.height)
let totalLabel = UILabel()
totalLabel.text = balanceAmount
totalLabel.tag = 1
totalLabel.font = UIFont.boldSystemFont(ofSize: 14)
totalLabel.textColor = UIColor.red
navigationBar.addSubview(totalLabel)
}
}
func getData() -> Void {
do{
dataInfo = try context.fetch(Owe.fetchRequest())
var total:Double = 0.00
for i in 0 ..< dataInfo.count {
total += dataInfo[i].amount as! Double
}
balanceAmount = "Balance: ₹" + (NSString(format: "%.2f", total as CVarArg) as String)
}
catch{
print("Fetching Failed")
}
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
let vc = segue.destination as! NewOweTableViewController
vc.dataInfo = selectedObject
selectedObject.removeAll()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
getData()
personTable.reloadData()
if (self.navigationController?.navigationBar.viewWithTag(1)?.isHidden == true){
self.navigationController?.navigationBar.viewWithTag(1)?.removeFromSuperview()
addTotalToNav()
}
}
}

Swift 3.0 Use below method to create NavigationBarTitle and NavigationBarSubTitle
func setTitle(title:String, subtitle:String) -> UIView {
let titleLabel = UILabel(frame: CGRect(x:0,y: -8 ,width: 0,height: 0))
titleLabel.backgroundColor = UIColor.clear
titleLabel.textColor = UIColor.black
titleLabel.font = UIFont.systemFont(ofSize: 22)
titleLabel.text = title
titleLabel.sizeToFit()
let subtitleLabel = UILabel(frame: CGRect(x:0,y:18,width: 0,height :0))
subtitleLabel.backgroundColor = UIColor.clear
subtitleLabel.textColor = UIColor.black
subtitleLabel.font = UIFont.systemFont(ofSize: 12)
subtitleLabel.text = subtitle
subtitleLabel.sizeToFit()
let titleView = UIView(frame: CGRect(x:0,y:0,width : max(titleLabel.frame.size.width, subtitleLabel.frame.size.width),height: 30))
titleView.addSubview(titleLabel)
titleView.addSubview(subtitleLabel)
let widthDiff = subtitleLabel.frame.size.width - titleLabel.frame.size.width
if widthDiff < 0 {
let newX = widthDiff / 2
subtitleLabel.frame.origin.x = abs(newX)
} else {
let newX = widthDiff / 2
titleLabel.frame.origin.x = newX
}
return titleView
}
Use this in viewDidLoad()
override func viewDidLoad() {
super.viewDidLoad()
self.navigationItem.titleView = setTitle(title: "My Events", subtitle: "Sub Title")
}

Here is the code, just set the titleView to your label:
let customLabel = UILabel()
// config your label here
navigationItem?.titleView = customLabel

You can use navigationBar.topItem?.titleView = totalLabel instead of navigationBar.addSubview(totalLabel).

Related

How to fix dynamic height for individual cells as UIautodimensions is not working

I am creating a wall page like twitter or Facebook in which user can post on the wall it can include image and just text. So based on the content the cell's heights must change, if the post is of one line the row height must be appropriate.
I tried using UITableViewAutomaticDimensions, but its not working with my code please do help me.
import UIKit
class wallPageViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
var tableOfApps : UITableView?
var appNames: [String]? = []
var apps: [wallPageModel]?
var dynamic_height : CGFloat = 150.0
var addPost : UITextField?
var readMore : UITextView?
func loadTableOfApps(){
//appNames = ["jkbajdba", "abfajfb", "akjbfkjag", "ahbfkajf" ]
let provider = wallPageProvider()
apps = provider.getApps()
let tableHeight = view.frame.size.height
tableOfApps = UITableView(frame: CGRect(x: 10, y: 60, width: 300, height: tableHeight))
tableOfApps!.delegate = self
tableOfApps!.dataSource = self
tableOfApps?.separatorStyle = UITableViewCellSeparatorStyle.none
//self.tableOfApps?.rowHeight = UITableViewAutomaticDimension
//self.tableOfApps?.estimatedRowHeight = UITableViewAutomaticDimension
print("load table of apps")
view.addSubview(tableOfApps!)
}
override func viewDidLoad() {
super.viewDidLoad()
loadTableOfApps()
loadAddPost()
tableOfApps?.estimatedRowHeight = 150.0
tableOfApps?.rowHeight = UITableViewAutomaticDimension
view.backgroundColor = UIColor(red: 232/255, green: 234/255, blue: 246/255, alpha: 1.0)
// Do any additional setup after loading the view.
}
func loadAddPost(){
addPost = UITextField(frame: CGRect(x: 10, y: 20, width: 300, height: 30))
addPost?.placeholder = "Stay safe, post a tip!"
addPost?.isUserInteractionEnabled = true
addPost?.borderStyle = UITextBorderStyle.roundedRect
addPost?.autocapitalizationType = .none
view.addSubview(addPost!)
addPost?.addTarget(self, action: #selector(writeComment), for: UIControlEvents.touchDown)
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
print("app coun\(apps!.count)")
return apps!.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
var cell : wallModelTableViewCell?
cell = tableView.dequeueReusableCell(withIdentifier: "cell") as? wallModelTableViewCell
if cell == nil {
cell = wallModelTableViewCell(style: UITableViewCellStyle.default, reuseIdentifier: "cell")
}
let app = apps![indexPath.row]//reading the array of data hence provider
//association of provider and view
//this is the processs from where view can read the data from provide
cell!.iconImageLabel!.image = app.icon
cell!.titleLabel!.text = app.title
cell?.backgroundColor = UIColor.white
cell!.commentsLabel?.image = app.comments_Label
cell?.commentsLabel?.center = CGPoint(x: tableView.frame.size.width/2, y: dynamic_height-20)
cell?.likeButtonLabel?.image = app.likeButton
cell?.likeButtonLabel?.center = CGPoint(x: (tableView.frame.size.width/2)-130, y: dynamic_height-20)
/*cell?.likeButtonLabel?.leftAnchor.constraint(equalTo: tableView.leftAnchor, constant: 50)*/
cell!.feedTextLabel!.text = app.feedText
cell?.feedTextLabel?.sizeToFit()//so that it can expand the data more than two lines
cell?.feedTextLabel?.backgroundColor = UIColor.clear
//Limiting UIlabel to 125 characters
if (cell?.feedTextLabel?.text.count)! > 125{
/*
let index = cell?.feedTextLabel?.text.index((cell?.feedTextLabel?.text.startIndex)!, offsetBy: 125)
cell?.feedTextLabel?.text = cell?.feedTextLabel?.text.substring(to: index!)
cell?.feedTextLabel?.text = cell?.feedTextLabel?.text.appending("...")*/
//cell?.feedTextLabel?.attributedText = NSAttributedString(string: "...readmore")
}
cell?.layer.cornerRadius = 6.0
cell?.isUserInteractionEnabled = false
cell?.titleLabel?.isUserInteractionEnabled = true
tableOfApps?.backgroundColor = UIColor.clear
tableOfApps?.backgroundView?.isOpaque = false
tableOfApps!.estimatedRowHeight = 150.0
tableOfApps!.rowHeight = UITableViewAutomaticDimension
print("table view cell for row")
/*let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector( self.labelAction(gesture:)))
cell?.feedTextLabel?.addGestureRecognizer(tap)
cell?.feedTextLabel?.isUserInteractionEnabled = true
tap.delegate = self as! UIGestureRecognizerDelegate*/
return cell!
}
/*#objc func labelAction(gesture: UITapGestureRecognizer){
}*/
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
print("height for row")
return UITableViewAutomaticDimension
}
func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat {
return 150.0
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Navigation
#objc func writeComment(){
let addComment = addCommentViewController()
navigationController?.pushViewController(addComment, animated: true)
}
/*
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
I want each row must have dynamic height as the content is provided by the user if the content contains 150 characters the height of the cell must be 200+ if content contains less than 125 characters the height must be as adequate to read.

iOS Charts in a tableview: correct use of a delegate and global zoom

I'm using iOS Charts in my project, and I've been able to embed my charts in a tableview (every cell will contain a chart, up to maximum number of possible entries to keep under control the performance).
I would like to use the 'touchMatrix' feature in order zoom the x axis on one chart (in a cell) and have all of the other visible charts to follow along with the zoom scale (the x axis), possibly with a vertical axis showing the Y value on every visible chart for that x coordinate, but I'm kind of stuck, since even the delegate methods such as 'chartValueNothingSelected' are not working (I probably got it wrong when I tried to associate the delegate to the chartview, since the chart it's embedded in the cell, and it's not the tipical case of associating the delegate to a view controller).
Assigning the delegate to the cell just doesn't seem to be working.
Any tips?
Thanks in advance.
Here is the code:
import UIKit
import Charts
class CustomChartCell: UITableViewCell, ChartViewDelegate {
#IBOutlet weak var lineChartView: LineChartView!
var yValues = [Double]()
var xValues = [Double]()
var chartColor = UIColor()
var channelName = ""
var yMin = 0.0
var yMax = 0.0
var yAvg = 0.0
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
self.lineChartView.noDataFont = UIFont.systemFont(ofSize: 28.0)
self.lineChartView.noDataText = NSLocalizedString("No chart data available", comment: "No Chart Data Available Title")
self.lineChartView.xAxis.labelPosition = .bottom
self.lineChartView.highlightPerTapEnabled = true
self.lineChartView.autoScaleMinMaxEnabled = true
self.lineChartView.chartDescription?.enabled = true
self.lineChartView.dragEnabled = true
self.lineChartView.setScaleEnabled(true)
self.lineChartView.pinchZoomEnabled = false
self.lineChartView.xAxis.gridLineDashLengths = [10, 10]
self.lineChartView.xAxis.gridLineDashPhase = 0
self.lineChartView.leftAxis.gridLineDashLengths = [5, 5]
self.lineChartView.leftAxis.drawLimitLinesBehindDataEnabled = true
self.lineChartView.rightAxis.enabled = false
let marker = BalloonMarker(color: UIColor(white: 180/255, alpha: 1),
font: .systemFont(ofSize: 12),
textColor: .white,
insets: UIEdgeInsets(top: 8, left: 8, bottom: 20, right: 8))
marker.chartView = self.lineChartView
marker.minimumSize = CGSize(width: 80, height: 40)
self.lineChartView.marker = marker
self.lineChartView.legend.form = .line
self.lineChartView.delegate = self
}
func setChart(_ xValues: [Double], _ yValues: [Double]) {
var dataEntries: [ChartDataEntry] = []
for i in 0..<xValues.count {
let dataEntry = ChartDataEntry(x: xValues[i], y: yValues[i])
dataEntries.append(dataEntry)
}
let chartDataSet = LineChartDataSet(values: dataEntries, label: self.channelName)
let chartData = LineChartData(dataSets: [chartDataSet])
chartDataSet.setColor(self.chartColor.withAlphaComponent(0.5))
chartDataSet.drawCirclesEnabled = false
chartDataSet.lineWidth = 2
chartDataSet.drawValuesEnabled = false
chartDataSet.highlightEnabled = true
chartDataSet.drawFilledEnabled = false
lineChartView.data = chartData
self.lineChartView!.leftAxis.axisMinimum = self.yValues.min()! - self.yValues.max()!*0.2
self.lineChartView!.leftAxis.axisMaximum = self.yValues.max()! + self.yValues.max()!*0.2
self.lineChartView!.chartDescription?.font = UIFont.systemFont(ofSize: 11.0)
self.lineChartView!.chartDescription?.text = "y_min: \(self.yMin), y_max: \(self.yMax), y_avg: \(self.yAvg)"
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
class ChartTableViewController: UITableViewController, ChartViewDelegate {
var dataSet : [LineChartData] = []
let data = LineChartData()
var channelNames : [String] = []
let channelColors = [UIColor.blue, UIColor.green, UIColor.red,
UIColor.orange, UIColor.purple, UIColor.darkGray]
var averageValues : [Double] = []
var minValues : [Double] = []
var maxValues : [Double] = []
var xValues : [[Double]] = []
var yValues : [[Double]] = []
#IBAction func chartZoomOut(_ sender: Any) {
tableView?.visibleCells.forEach { cell in
if let cell = cell as? CustomChartCell {
cell.lineChartView.zoomOut()
}
}
}
#IBAction func chartZoom100(_ sender: Any) {
tableView?.visibleCells.forEach { cell in
if let cell = cell as? CustomChartCell {
cell.lineChartView.zoomToCenter(scaleX: 0, scaleY: 0)
}
}
}
#IBAction func chartZoomIn(_ sender: Any) {
tableView?.visibleCells.forEach { cell in
if let cell = cell as? CustomChartCell {
cell.lineChartView.zoomIn()
}
func chartValueNothingSelected(_ chartView: ChartViewBase) {
chartView.chartDescription?.text = ""
}
func chartScaled(chartView: ChartViewBase, scaleX: CGFloat, scaleY: CGFloat) {
print(scaleX)
print(scaleY)
}
func chartValueSelected(_ chartView: ChartViewBase, entry: ChartDataEntry, highlight: Highlight) {
chartView.chartDescription?.text = "x: \(entry.x), y: \(entry.y), y_min: \(minValues[0]), y_max: \(maxValues[0]), y_avg: \(averageValues[0])"
chartView.reloadInputViews()
}
override func viewDidLoad() {
super.viewDidLoad()
self.tableView.isEditing = false
self.editButtonItem.title = NSLocalizedString("Edit", comment: "Edit Title")
self.tableView.separatorColor = UIColor.clear
self.navigationItem.rightBarButtonItem = self.editButtonItem
self.loadFile()
self.tableView.reloadData()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
self.tableView.isEditing = false
self.editButtonItem.title = NSLocalizedString("Edit", comment: "Edit Title")
}
// MARK: Load Chart File
func loadFile() {
// Try to load the file content
do {
// get the documents folder url
let documentDirectoryURL = try FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: true)
// create the destination url for the text file to be saved
let fileDestinationUrl = documentDirectoryURL.appendingPathComponent(Constants.CHART_FILE_NAME)
// reading from disk
do {
let file = try String(contentsOf: fileDestinationUrl)
let newFile = file.replacingOccurrences(of: "\r", with: "") // Get rid of additional new lines
let cleanChannels = self.generateCleanChannels(newFile) // // a function used to retrieve the channels from the file (since the file it's not a plain CSV file but something different)
channelNames.removeAll()
dataSet.removeAll()
channelNames = self.getChannelNames(newFile) // a function used to retrieve the channel names from the file (since the file it's not a plain CSV file but something different)
var lineChartEntry = [ChartDataEntry]()
data.clearValues()
for (index,channel) in cleanChannels.enumerated() {
if (index <= Constants.MAX_CHART_CHANNELS) {
let csvImage = CSV(string: channel, delimiter: ";")
var y_max = 0.0
var firstXValueSampled : Bool = false
var firstXValue : Double = 0.0
var average = 0.0
var min = 0.0
var max = 0.0
var count = 0
var new_xValues : [Double] = []
var new_yValues : [Double] = []
csvImage.enumerateAsDict { dict in
print(dict["X_Value"]!)
new_xValues.append(Double(dict["X_Value"]!)!)
new_yValues.append(Double(dict["Y_Value"]!)!)
if !firstXValueSampled {
firstXValueSampled = true
firstXValue = Double(dict["X_Value"]!)!
}
average = average + Double(dict["Y_Value"]!)!
count = count + 1
let value = ChartDataEntry(x: (Double(dict["X_Value"]!)! - firstXValue), y: Double(dict["Y_Value"]!)! )
lineChartEntry.append(value)
if Double(dict["Y_Value"]!)! > max {
max = Double(dict["Y_Value"]!)!
}
if Double(dict["Y_Value"]!)! < min {
min = Double(dict["Y_Value"]!)!
}
if Double(dict["Y_Value"]!)! > y_max {
y_max = Double(dict["Y_Value"]!)!
}
}
xValues.append(new_xValues)
yValues.append(new_yValues)
average = average / Double(count)
averageValues.append(average)
minValues.append(min)
maxValues.append(max)
let line = LineChartDataSet(values: lineChartEntry, label: channelNames[index])
line.axisDependency = .left
line.colors = [channelColors[index]] // Set the color
line.setColor(channelColors[index].withAlphaComponent(0.5))
line.setCircleColor(channelColors[index])
line.lineWidth = 2.0
line.circleRadius = 3.0
line.fillAlpha = 65 / 255.0
line.fillColor = channelColors[index]
line.highlightColor = UIColor(red: 244/255, green: 117/255, blue: 117/255, alpha: 1)
line.drawCircleHoleEnabled = false
line.highlightLineWidth = 2.0
line.drawHorizontalHighlightIndicatorEnabled = true
data.setValueFont(.systemFont(ofSize: 9))
data.addDataSet(line) // Add the line to the dataSet
let newData = LineChartData()
newData.setValueFont(.systemFont(ofSize: 9))
newData.addDataSet(line)
dataSet.append(newData)
}
}
} catch let error as NSError {
print("error loading contentsOf url \(fileDestinationUrl)")
print(error.localizedDescription)
}
} catch let error as NSError {
print("error getting documentDirectoryURL")
print(error.localizedDescription)
}
}
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return dataSet.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cellIdentifier = "CustomChartCell"
let cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier,
for: indexPath) as! CustomChartCell
cell.lineChartView.delegate = self
if dataSet.count > 0 {
cell.xValues = xValues[indexPath.row]
cell.yValues = yValues[indexPath.row]
cell.chartColor = channelColors[indexPath.row]
cell.channelName = channelNames[indexPath.row]
cell.yMin = minValues[indexPath.row]
cell.yMax = maxValues[indexPath.row]
cell.yAvg = averageValues[indexPath.row]
cell.lineChartView.leftAxis.axisMaximum = cell.yValues.max()! + 1
cell.lineChartView.leftAxis.axisMinimum = cell.yValues.min()! - 1
cell.setChart(cell.xValues, cell.yValues)
} else {
cell.lineChartView.clearValues()
}
return cell
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
//tableView.deselectRow(at: indexPath, animated: true)
let selectedCell = tableView.cellForRow(at: indexPath) as! CustomChartCell
selectedCell.contentView.backgroundColor = UIColor.lightGray
//let currentMatrix = selectedCell.lineChartView.viewPortHandler.touchMatrix
//let selectedCell:UITableViewCell = tableView.cellForRow(at: indexPath)! as! CustomChartCell
//selectedCell.contentView.backgroundColor = UIColor.lightGray
//let currentMatrix = selectedCell.lineChartView.viewPortHandler.touchMatrix
/*
tableView.visibleCells.forEach { cell in
if let cell = cell as? CustomChartCell {
if cell.channelName != selectedCell.channelName {
cell.lineChartView.viewPortHandler.refresh(newMatrix: currentMatrix, chart: cell.lineChartView, invalidate: true)
}
}
}
*/
}
override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 250
}
override func tableView(_ tableView: UITableView, editingStyleForRowAt indexPath: IndexPath) -> UITableViewCell.EditingStyle {
return .none
}
override func tableView(_ tableView: UITableView, shouldIndentWhileEditingRowAt indexPath: IndexPath) -> Bool {
return false
}
override func setEditing (_ editing:Bool, animated:Bool)
{
super.setEditing(editing,animated:animated)
if (self.isEditing) {
//self.editButtonItem.title = "Editing"
self.editButtonItem.title = NSLocalizedString("Done", comment: "Done Title")
}
else {
self.editButtonItem.title = NSLocalizedString("Edit", comment: "Edit Title")
}
}
override func tableView(_ tableView: UITableView, moveRowAt sourceIndexPath: IndexPath, to destinationIndexPath: IndexPath) {
let movedObject = self.dataSet[sourceIndexPath.row]
dataSet.remove(at: sourceIndexPath.row)
dataSet.insert(movedObject, at: destinationIndexPath.row)
}
}

Filtering UItableview Swift IOS

I am trying to filter a UITableView based on variables that have been passed back from another VC which is a Eureka form handling the filter UI.
I would like to filter the tableview based on these two variables :
var filterByPrice: Float?
var filteredRentalTypes: Set<String>?
I have got the price filter working but I am having trouble filtering with the rental type. There may be a more efficient way of doing this but this is my code so far. With my current code I get an 'index out of range' crash for the rental type filter.
This is my TableViewVC:
class RentalTableViewVC: UIViewController, UITableViewDataSource, UITableViewDelegate {
var rentalsArray = [Rental]()
var filteredArrary = [Rental]()
var myRentals = [String]()
var filterByPrice: Float?
var filteredRentalTypes: Set<String>?
static var imageCache: NSCache<NSString, UIImage> = NSCache()
#IBOutlet weak var tableView: UITableView!
var hidingBarMangar: HidingNavigationBarManager?
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "toDetailVC" {
let destination = segue.destination as? DetailVC
let value = tableView.indexPathForSelectedRow?.row
if filteredArrary.count != 0 {
destination?.emailAdress = filteredArrary[value!].email!
destination?.bond = filteredArrary[value!].bond!
destination?.dateAval = filteredArrary[value!].dateAval!
destination?.pets = filteredArrary[value!].pets!
destination?.rent = filteredArrary[value!].price!
destination?.rentalTitle = filteredArrary[value!].title!
destination?.imageURL = filteredArrary[value!].imageURL!
destination?.des = filteredArrary[value!].description!
destination?.rentalType = filteredArrary[value!].rentalType!
destination?.streetName = filteredArrary[value!].streetName!
destination?.city = filteredArrary[value!].city!
destination?.postcode = filteredArrary[value!].postcode!
} else {
destination?.emailAdress = rentalsArray[value!].email!
destination?.bond = rentalsArray[value!].bond!
destination?.dateAval = rentalsArray[value!].dateAval!
destination?.pets = rentalsArray[value!].pets!
destination?.rent = rentalsArray[value!].price!
destination?.rentalTitle = rentalsArray[value!].title!
destination?.imageURL = rentalsArray[value!].imageURL!
destination?.des = rentalsArray[value!].description!
destination?.rentalType = rentalsArray[value!].rentalType!
destination?.streetName = rentalsArray[value!].streetName!
destination?.city = rentalsArray[value!].city!
destination?.postcode = rentalsArray[value!].postcode!
}
}
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if filteredArrary.count != 0 {
return filteredArrary.count
} else {
return rentalsArray.count
}
}
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
var rental = rentalsArray[indexPath.row]
if self.filteredArrary.count != 0 {
rental = filteredArrary[indexPath.row]
}
if let cell = tableView.dequeueReusableCell(withIdentifier: "cell") as? RentalCell {
var rentalImage = ""
if rental.imageURL != nil {
rentalImage = rental.imageURL!
}
if let img = RentalTableViewVC.imageCache.object(forKey: rentalImage as NSString) {
cell.configureCell(rental: rental, image: img)
return cell
} else {
cell.configureCell(rental: rental, image: nil)
return cell
}
} else {
return RentalCell()
}
}
#IBAction func backPressed(_ sender: Any) {
dismiss(animated: true, completion: nil)
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
hidingBarMangar?.viewWillAppear(animated)
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
hidingBarMangar?.viewDidLayoutSubviews()
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
hidingBarMangar?.viewWillDisappear(animated)
}
override func viewDidLoad() {
super.viewDidLoad()
tableView.dataSource = self
tableView.dataSource = self
//Firebase observer
DataService.ds.DBrefRentals.observe(.value) { (snapshot) in
self.rentalsArray = []
self.filteredArrary = []
if let snapshots = snapshot.children.allObjects as? [DataSnapshot] {
for snap in snapshots {
if let dicOfRentals = snap.value as? Dictionary<String,AnyObject> {
let key = snap.key
let rental = Rental(postID: key, userData: dicOfRentals)
self.rentalsArray.append(rental)
//Placing filtered items in the filtered array
if self.filterByPrice != nil {
let priceAsFloat = (rental.price! as NSString).floatValue
if self.filterByPrice! >= priceAsFloat {
self.filteredArrary.append(rental)
}
}
if self.filteredRentalTypes != nil {
for rentals in self.filteredRentalTypes! {
if rental.rentalType == rentals {
print("******hh\(String(describing: self.filteredRentalTypes))")
self.filteredArrary.append(rental)
}
}
}
}
}
self.tableView.reloadData()
}
}
addHidingBar()
}
override func viewDidAppear(_ animated: Bool) {
print("**********\(String(describing: filterByPrice)))")
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
rentalsArray[indexPath.row].incrimentViews()
let postViewsToFB = DataService.ds.DBrefRentals.child(rentalsArray[indexPath.row].postID!)
postViewsToFB.child("views").setValue(rentalsArray[indexPath.row].views)
performSegue(withIdentifier: "toDetailVC" , sender: nil)
}
func addHidingBar() {
let extensionView = UIView(frame: CGRect(x: 0, y: 0, width: view.frame.size.width, height: 40))
extensionView.layer.borderColor = UIColor.lightGray.cgColor
extensionView.layer.borderWidth = 1
extensionView.backgroundColor = UIColor(white: 230/255, alpha: 1)
/*let label = UILabel(frame: extensionView.frame)
label.text = "Extension View"
label.textAlignment = NSTextAlignment.center
extensionView.addSubview(label) */
let btn = UIButton(frame: CGRect(x: 20, y: 15, width: 75, height: 10))
btn.setTitle("Filter", for: .normal)
let btnColour = UIColor(displayP3Red: 0.0, green: 122.0/255.0, blue: 1.0, alpha: 1.0)
btn.setTitleColor(btnColour, for: .normal)
btn.titleLabel?.font = headerFont
btn.addTarget(self, action: #selector(filterBtnPressed), for: .touchUpInside)
extensionView.addSubview(btn)
hidingBarMangar = HidingNavigationBarManager(viewController: self, scrollView: tableView)
hidingBarMangar?.addExtensionView(extensionView)
}
#objc func filterBtnPressed() {
performSegue(withIdentifier: "toFilterVC", sender: nil)
}
}
You may return different array in numberOfRows and their sizes may be different so check count before indexing any array as if array count != 0 doesn't mean you can index it with index path.row that may be greater then 0 ,Change this line in cellForRow
if self.filteredArrary.count != 0 {
rental = filteredArrary[indexPath.row]
}
to
if indexPath.row < self.filteredArrary.count {
rental = filteredArrary[indexPath.row]
}

Swift3 SearchBar Tutorial with TableView Sections

Does somebody have a good Tutorial for a Search Bar with Sections? I did not found a good one yet. Or maybe you can help me straight with my project!?
The section Title is static but i integrated some customized subtitles to show the regions and the total time i spend to make all this Locations(Liegenschaften) in this section. I create this values in the function createWinterdienstDetail. This values should not change when i search for one Location.
I get the Values for my tableview from a different ViewController as
var AllWinterdienstTourInfos: [Int:[Int:[String]]] = [:] // Section - Locationnumber - Locationinformations
Here is my ViewController File:
import UIKit
class WinterdienstTourVC: UIViewController {
var sections = ["Tour 1","Tour 2","Tour 3","Tour 4"]
var LiegenschaftDetail: [String] = []
// VARIABLEN WINTERDIENST
var WinterdienstregionTour1: [String] = []
...
var WinterdienstregionTour15: [String] = []
var WinterdienstaufwandTour1String: [String] = []
...
var WinterdienstaufwandTour15String: [String] = []
var WinterdienstaufwandTour1: [Double] = []
...
var WinterdienstaufwandTour15: [Double] = []
var Totaltouraufwand1 = Double()
...
var Totaltouraufwand15 = Double()
var AllWinterdienstTourInfos: [Int:[Int:[String]]] = [:]
// Initialisierung
#IBOutlet weak var tableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
createWinterdienstDetail()
tableView.delegate = self
tableView.dataSource = self
tableView.tableFooterView = UIView(frame: CGRect.zero)
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if (segue.identifier == "WinterdienstDetailSegue1") {
let DetailviewController = segue.destination as! WinterdienstLiegenschaftDetailVC
DetailviewController.LiegenschaftDetail = LiegenschaftDetail
}
}
func createWinterdienstDetail() {
if let liegenschaftenTour1 = AllWinterdienstTourInfos[0],
let liegenschaftenTour2 = AllWinterdienstTourInfos[1],
let liegenschaftenTour3 = AllWinterdienstTourInfos[2],
let liegenschaftenTour4 = AllWinterdienstTourInfos[3]{
self.myGroup.enter()
// DETAILS TOUR 1
for liegenschaften in liegenschaftenTour1.keys {
WinterdienstregionTour1.append(AllWinterdienstTourInfos[0]![liegenschaften]![6])
WinterdienstaufwandTour1String.append(AllWinterdienstTourInfos[0]![liegenschaften]![15])
for i in 0 ..< WinterdienstregionTour1.count-1 {
var j = WinterdienstregionTour1.count - 1
while(j > i) {
if WinterdienstregionTour1[i] == WinterdienstregionTour1[j] {
WinterdienstregionTour1.remove(at: j)
}
j -= 1
}
}
}
for WinterdienstaufwandTour1Array in WinterdienstaufwandTour1String {
WinterdienstaufwandTour1.append((WinterdienstaufwandTour1Array as NSString).doubleValue)
}
Totaltouraufwand1 = WinterdienstaufwandTour1.reduce(0,+)
// DETAILS TOUR 2
// DETAILS TOUR 3
// DETAILS TOUR 4
self.myGroup.leave()
self.myGroup.notify(queue: .main) {}
DispatchQueue.main.async {}
} // ENDE Function Create Winterdienst
} // ENDE CLASS WinterdienstTourVC
// DataSource-Methoden
extension WinterdienstTourVC: UITableViewDataSource {
func numberOfSections(in tableView: UITableView) -> Int
{
return sections.count
}
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let view = UIView()
// SECTION HEADER ALLGEMEIN
view.backgroundColor = UIColor.lightGray
// SECTION HEADER TOUR - NR
let tournr = UILabel()
tournr.text = sections[section]
tournr.font = UIFont.boldSystemFont(ofSize: 20.0)
tournr.frame = CGRect(x: 15,y:0, width: 100, height: 30)
view.addSubview(tournr)
// SECTION HEADER - TOURREGION / TOURAUFWAND
let tourregion = UILabel()
WinterdienstregionTour1.sort()
WinterdienstregionTour1.sort()
WinterdienstregionTour3.sort()
WinterdienstregionTour4.sort()
switch section{
case 0:
let tourregion1 = WinterdienstregionTour1.joined(separator: ", ")
tourregion.text = "\(tourregion1)"
case 1:
let tourregion2 = WinterdienstregionTour2.joined(separator: ", ")
tourregion.text = "\(tourregion2)"
.....
default:
tourregion.text = "Keine Angaben"
}
tourregion.font = UIFont.systemFont(ofSize: 16)
tourregion.frame = CGRect(x: 15,y:22, width: 200, height: 30)
view.addSubview(tourregion)
let touraufwand = UILabel()
switch section{
case 0:
touraufwand.text = "\(Totaltouraufwand1) h"
case 1:
touraufwand.text = "\(Totaltouraufwand2) h"
....
default:
touraufwand.text = "Keine Angaben"
}
touraufwand.frame = CGRect(x: -5,y:12, width: 370, height: 30)
touraufwand.font = UIFont.boldSystemFont(ofSize: 22.0)
touraufwand.textAlignment = .right
view.addSubview(touraufwand)
return view
}
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 50
}
func tableView(_ tableView: UITableView,
numberOfRowsInSection section: Int) -> Int
{
switch section{
case 0:
return self.AllWinterdienstTourInfos[0]!.count
// self.WinterdienstadressTourAll[0]!.count
case 1:
return self.AllWinterdienstTourInfos[1]!.count
//self.WinterdienstAlltourinfosAll[1]![section]!.count
....
default:
return 1
}
}
func tableView(_ tableView: UITableView,
cellForRowAt indexPath: IndexPath)
-> UITableViewCell
{
// versuchen, eine Zelle wiederzuverwenden
var cell = tableView.dequeueReusableCell(
withIdentifier: "cell")
if cell == nil {
// nicht möglich, daher neue Zelle erzeugen
cell = UITableViewCell(
style: .default, reuseIdentifier: "cell")
}
// Eigenschaften der Zelle einstellen
cell!.textLabel!.text = AllWinterdienstTourInfos[indexPath.section]![indexPath.row]?[4]
cell!.textLabel!.adjustsFontSizeToFitWidth = true
cell!.textLabel!.textAlignment = .left
// Zelle zurückgeben
return cell!
}
}
// TableView-Delegates
extension WinterdienstTourVC: UITableViewDelegate {
func tableView(_ tableView: UITableView,
didSelectRowAt indexPath: IndexPath)
{
LiegenschaftDetail = AllWinterdienstTourInfos[indexPath.section]![indexPath.row]!
performSegue(withIdentifier: "WinterdienstDetailSegue1", sender: self)
}
}

UITableView scroll freezes when scrolling fast

I am using custom tableview cells in a tableview. The data is loaded from the server and height calculation of that particular cell is done inside the cell only.
<iframe width="560" height="315" src="https://www.youtube.com/embed/h-FjYkSBuNM" frameborder="0" allowfullscreen></iframe>
I am attaching the code for tableview cell for row at indexpath, custom cell method and code for get request.
class QuesAnsFeedTableViewCell: UITableViewCell {
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
setup()
}
override func layoutSubviews() {
super.layoutSubviews()
self.questionLabel.preferredMaxLayoutWidth = questionLabel.frame.width
self.answerLabel.preferredMaxLayoutWidth = answerLabel.frame.width
super.layoutSubviews()
}
func setup(){
topLeftLabel = UILabel()
topLeftLabel.font = UIFont(name: regularFont, size: 12)
topLeftLabel.text = "Yesterday"
topLeftLabel.textColor = CommonFunctions.hexStringToUIColor(hex: lightGray)
topRightLabel = UILabel()
topRightLabel.font = UIFont(name: regularFont, size: 12)
topRightLabel.textColor = CommonFunctions.hexStringToUIColor(hex: lightGray)
topRightLabel.text = ""
topRightLabel.textAlignment = .right
questionLabel = UILabel()
questionLabel.font = UIFont(name: mediumFont, size: 14)
questionLabel.text = "First Ques Comes Here and ans will be below this question"
questionLabel.numberOfLines = 0
questionLabel.lineBreakMode = .byWordWrapping
userImageView = UIImageView()
userImageView.backgroundColor = .purple
userImageView.layer.cornerRadius = CGFloat(sidePadding)/2
userImageView.clipsToBounds = true
userNameLabel = UILabel()
userNameLabel.font = UIFont(name: regularFont, size: 12)
userNameLabel.text = ""
answerLabel = UILabel()
answerLabel.font = UIFont(name: regularFont, size: 14)
answerLabel.text = ""
answerLabel.numberOfLines = 0
answerLabel.lineBreakMode = .byWordWrapping
viewOtherAnswerLabel = UILabel()
viewOtherAnswerLabel.font = UIFont(name: mediumFont, size: 12)
viewOtherAnswerLabel.text = ""
viewOtherAnswerLabel.textAlignment = .center
viewOtherAnswerLabel.textColor = CommonFunctions.hexStringToUIColor(hex: lightGray)
writeAnswerLabel = UILabel()
writeAnswerLabel.font = UIFont(name: mediumFont, size: 14)
writeAnswerLabel.backgroundColor = CommonFunctions.hexStringToUIColor(hex: crispBlue)
writeAnswerLabel.text = "Write Answer"
writeAnswerLabel.textAlignment = .center
writeAnswerLabel.textColor = .white
tapGesture = UITapGestureRecognizer(target: self, action: #selector(self.tappedCell(sender:)))
tapGesture.numberOfTapsRequired = 1
self.addGestureRecognizer(tapGesture)
// self.addSubview(likeButton)
// self.addSubview(descriptionLabel)
}
func updateData(data:NSDictionary) -> CGFloat{
if let viewCount = data["vc"] {
topRightLabel.text = "\(viewCount) read"
}
if let ques = data["q"] as? String{
topLeftLabel.frame = CGRect(x:sidePadding/2, y: 2*sidePaddingForCollectionCells, width: screenWidth/2-sidePadding, height: Int(CommonFunctions.calculateHeight(inString: topLeftLabel.text!, forFont: topLeftLabel.font, andWidthOfLabel: CGFloat(screenWidth/2))))
topRightLabel.frame = CGRect(x: screenWidth/2, y: 2*sidePaddingForCollectionCells, width: screenWidth/2-sidePadding/2, height: Int(topLeftLabel.frame.height))
let newHeight = CommonFunctions.calculateHeight(inString: ques,forFont:questionLabel.font,andWidthOfLabel:questionLabel.frame.width)
questionLabel.frame = CGRect(x:sidePadding/2 ,y: Int(topLeftLabel.frame.maxY)+sidePaddingForCollectionCells,width: screenWidth - sidePadding, height: Int(ceil(Float(newHeight))))
questionLabel.text = ques
self.addSubview(topLeftLabel)
self.addSubview(topRightLabel)
self.addSubview(questionLabel)
// questionLabel.attributedText = CommonFunctions.justifiedText(string: ques)
}
if let user = data.object(forKey: "user") as? NSDictionary{
if let usrName = user.value(forKey: "name"){
userNameLabel.text = "\(usrName)"
}
if let imgLink = user["image"] as? String{
if let url = URL(string: imgLink){
userImageView.sd_setImage(with: url,placeholderImage:#imageLiteral(resourceName: "placeholderImage"))
}
}
}
if let otherAnswer = data.value(forKey: "cc") {
viewOtherAnswerLabel.text = "View Other Answer \(otherAnswer)"
}
if let ans = data.value(forKey: "comt") as? String{
answered = true
userImageView.frame = CGRect(x: sidePadding/2, y: Int(questionLabel.frame.maxY)+2*sidePaddingForCollectionCells, width: sidePadding, height: sidePadding)
userNameLabel.frame = CGRect(x: 3*sidePadding/2+2*sidePaddingForCollectionCells, y:Int(questionLabel.frame.maxY)+sidePaddingForCollectionCells, width: screenWidth-2*sidePadding, height: Int(topLeftLabel.frame.height))
let newHeight = CommonFunctions.calculateHeight(inString: ans,forFont:answerLabel.font,andWidthOfLabel:answerLabel.frame.width)
let frame = CGRect(x: 3*sidePadding/2+2*sidePaddingForCollectionCells, y:Int(userNameLabel.frame.maxY) + sidePaddingForCollectionCells, width: screenWidth-2*sidePadding-2*sidePaddingForCollectionCells, height: Int(ceil(Float(newHeight))))
answerLabel.frame = frame
answerLabel.text = ans
viewOtherAnswerLabel.frame = CGRect(x: 0, y: Int(answerLabel.frame.maxY)+2*sidePaddingForCollectionCells, width: screenWidth, height: 2*sidePadding/3)
self.addSubview(userImageView)
self.addSubview(userNameLabel)
self.addSubview(answerLabel)
self.addSubview(viewOtherAnswerLabel)
writeAnswerLabel.removeFromSuperview()
return viewOtherAnswerLabel.frame.maxY
}
else{
answered = false
writeAnswerLabel.frame = CGRect(x: 0, y:Int(questionLabel.frame.maxY) + 2*sidePaddingForCollectionCells, width: screenWidth, height: sidePadding)
self.addSubview(writeAnswerLabel)
userImageView.removeFromSuperview()
userNameLabel.removeFromSuperview()
answerLabel.removeFromSuperview()
viewOtherAnswerLabel.removeFromSuperview()
return writeAnswerLabel.frame.maxY
}
}
TableView Code
class GenericView: UIView ,UITableViewDelegate,UITableViewDataSource {
var tableView:UITableView!
var viewFrame = CGRect()
var parentView = ""
var discussViewHeight = [Int:CGFloat]()
var nextUrlPath = ""
var currentUrlPath = ""
private var sliderLabelsText = ["Favourites","Sign In"]
private var tableBlocks = [NSDictionary]()
override init(frame: CGRect) {
super.init(frame: frame)
viewFrame = frame
setup()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
if viewFrame != CGRect() {
setup()
}
}
public func updateView(){
viewFrame = self.frame
tableView.frame = (viewFrame)
getRequest()
}
func getRequest(){
currentUrlPath = baseUrl+nextUrlPath
if parentView == discussView{
// let url = baseUrl + nextUrlPath
Alamofire.request(currentUrlPath).responseJSON { response in
if let dict = response.result.value as? [String:AnyObject]{
if (dict["msc"]) as? String == "700", let blocks = dict["blocks"] as? NSArray{
self.nextUrlPath = (dict["next"] as? String ?? "")
for block in blocks{
if let blk = block as? NSDictionary{
if blk.value(forKey: "ty") as? String == "qa"{
self.tableBlocks.append(blk)
}
appDelegate.tableBlocks.append(blk)
}
}
DispatchQueue.main.async(execute: { () -> Void in
self.refreshControl.endRefreshing()
self.tableView.reloadData()
})
}
else{
DispatchQueue.main.async(execute: { () -> Void in
self.currentUrlPath = ""
self.getRequest()
})
}
}
}
return
}
}
func setup(){
backgroundColor = UIColor.white
tableView = UITableView(frame: viewFrame, style: .grouped)
tableView.delegate = self
tableView.dataSource = self
self.addSubview(tableView)
registerCells()
}
//MARK: TableView DataSource Methods
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if parentView == discussView{
return 1
}
return 0
}
func numberOfSections(in tableView: UITableView) -> Int {
if parentView == discussView{
return tableBlocks.count
}
return 0
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if (parentView == discussView){
var cell:QuesAnsFeedTableViewCell? = tableView.dequeueReusableCell(withIdentifier: quesAnsFeedViewCellIdentifier, for: indexPath) as? QuesAnsFeedTableViewCell
if (cell == nil){
cell = QuesAnsFeedTableViewCell(style: .default, reuseIdentifier: quesAnsFeedViewCellIdentifier)
}
cell?.selectionStyle = .none
discussViewHeight[indexPath.section] = (cell?.updateData(data: tableBlocks[indexPath.section]))!
cell?.setNeedsLayout()
cell?.layoutIfNeeded()
return cell!
}
return UITableViewCell()
}
//MARK: TableView Delegate Methods
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
if parentView == discussView{
return discussViewHeight[indexPath.section] ?? 0
}
return 0
}
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
if parentView == discussView{
return sectionHeaderView
}
return UIView()
}
func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
if parentView == discussView && indexPath.section+5 > tableBlocks.count{
if currentUrlPath != baseUrl + nextUrlPath{
getRequest()
}
}
}
}
I have deleted some code from classes just to keep the size of question small.
The call for next fetch will depend on the indexpath of cell which is currently being displayed and the function which fetches the content from server will be getRequest().
Any help is greatly appreciated

Resources