Anchoring UILabel in UITableView section header - swift

I'm getting a misalignment of a UILabel (variable name: wrongCountLabel) in a UITableView section header, as it's programatically set to a fixed x and y coordinate. These coordinates work fine for smaller screens but fall short of the right hand side on larger screens (see screen dumps below).
Since I created the section header in code I've tried to programatically anchor the trailing edge of the "Wrong (times)" label to the trailing edge of UITableView. When I run the widget, it says it's unable to load the data.
//
// TodayViewController.swift
// Widget
//
// Created by on 10/02/2019.
// Copyright © 2019. All rights reserved.
//
import UIKit
import NotificationCenter
class TodayViewController: UIViewController, NCWidgetProviding, UITableViewDataSource, UITableViewDelegate {
#IBOutlet weak var tableView: UITableView!
var words = [String]()
var sortedPracticeWords = [String]()
var chosenLanguage = String()
let wordsString = "Words"
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view from its nib.
if let defaults = UserDefaults(suiteName: "group.co.uk.tirnaelectronics.polyglot") {
if let savedLanguage = defaults.object(forKey: "languageChosen") as? String {
print("savedLanguage is: \(savedLanguage)")
chosenLanguage = savedLanguage
if let savedWords = defaults.object(forKey: "\(chosenLanguage)\(wordsString)") as? [String] {
words = savedWords
}
}
}
extensionContext?.widgetLargestAvailableDisplayMode = .expanded
sortPracticeWords()
}
func widgetActiveDisplayModeDidChange(_ activeDisplayMode: NCWidgetDisplayMode, withMaximumSize maxSize: CGSize) {
if activeDisplayMode == .compact {
preferredContentSize = CGSize(width: 0, height: 110)
} else {
preferredContentSize = CGSize(width: 0, height: 440)
}
}
func widgetPerformUpdate(completionHandler: (#escaping (NCUpdateResult) -> Void)) {
// Perform any setup necessary in order to update the view.
// If an error is encountered, use NCUpdateResult.Failed
// If there's no update required, use NCUpdateResult.NoData
// If there's an update, use NCUpdateResult.NewData
completionHandler(NCUpdateResult.newData)
}
func sortPracticeWords() {
var practiceWords = [String]()
for i in 1..<words.count {
if Int(words[i - 1].components(separatedBy: "::")[2]) ?? 0 > 0 {
practiceWords.append(words[i - 1])
}
}
var sortedAboveIndex = practiceWords.count
var swaps = 0
var tempPracticeWord = String()
repeat {
var lastSwapIndex = 0
for i in 1..<sortedAboveIndex {
if Int(practiceWords[i - 1].components(separatedBy: "::")[2])! < Int(practiceWords[i].components(separatedBy: "::")[2])! {
tempPracticeWord = practiceWords[i]
practiceWords[i] = practiceWords[i - 1]
practiceWords[i - 1] = tempPracticeWord
lastSwapIndex = i
swaps += 1
}
}
sortedAboveIndex = lastSwapIndex
} while (sortedAboveIndex != 0)
sortedPracticeWords = practiceWords
print("sortedPracticeWords are: \(sortedPracticeWords)")
print("practiceWords is sorted in \(swaps) swaps.")
}
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return sortedPracticeWords.count
}
internal func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let view = UIView()
view.backgroundColor = UIColor(white: 1, alpha: 0.2)
let languageLabel = UILabel()
languageLabel.text = "\(chosenLanguage.capitalized)"
languageLabel.frame = CGRect(x: 10, y: 5, width: 170, height: 20)
//languageLabel.leadingAnchor.constraint(equalTo: tableView.layoutMarginsGuide.leadingAnchor).isActive = true
view.addSubview(languageLabel)
let wrongCountLabel = UILabel()
wrongCountLabel.text = "Wrong (times)"
wrongCountLabel.textAlignment = .left
wrongCountLabel.frame = CGRect(x: 180, y: 5, width: 120, height: 20)
//wrongCountLabel.trailingAnchor.constraint(equalTo: tableView.layoutMarginsGuide.trailingAnchor).isActive = true
view.addSubview(wrongCountLabel)
return view
}
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 30
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell:TodayCustomCell = self.tableView.dequeueReusableCell(withIdentifier: "PracticeWord") as! TodayCustomCell
let sortedPracticeWord = sortedPracticeWords[indexPath.row]
print("practiceWord is: \(sortedPracticeWord)")
let split = sortedPracticeWord.components(separatedBy: "::")
cell.practiceWord.textColor = UIColor(white: 1, alpha: 0.75)
cell.selectedBackgroundView = UIView()
cell.selectedBackgroundView!.backgroundColor = UIColor(white: 1, alpha: 0.20)
cell.practiceWord.frame = CGRect(origin: CGPoint(x: 10, y: 10), size: CGSize(width: 200, height: 40))
cell.wrongCount.frame = CGRect(origin: CGPoint(x: 210, y: 10), size: CGSize(width: 100, height: 40))
cell.practiceWord?.text = split[1]
cell.wrongCount?.text = split[2]
print("cell is: \(cell)")
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
/*if let cell = tableView.cellForRow(at: indexPath) {
let practiceWord = sortedPracticeWords[indexPath.row]
let split = practiceWord.components(separatedBy: "::")
cell.detailTextLabel?.text = split[2]
print("Detail cell is: \(cell)")
}*/
}
}
The right hand screen should display like the left hand screen, only on a bigger screen.
I need some code that anchors UILabels so they work regardless of user's screen size.

Would changing:
wrongCountLabel.textAlignment = .left
To
wrongCountLabel.textAlignment = .right
Help?

Related

TableView displaying same array filtered elements even though array elements not filtered

enter image description here I have 2 buttons and two array list items which shows fruit names and color of the fruit. I implemented search functionality to search fruit and color. The issue here is
Tap on 1st button shows fruit names in a tableview.
Filtered a fruit with name. It retrieves a fruit back
Now tap on outside of the tableview. It dismisses the tableview
Tap on second button fruit color.
Issue arrises. It showing first array elements with search keyword same I entered in the earlier search. Here is my code and screen shots for reference. Where I need to modify the code. Any help is appreciated.
import UIKit
class Cell : UITableViewCell {
}
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, UISearchBarDelegate{
#IBOutlet weak var selectFruit: UIButton! {
didSet {
selectFruit.layer.cornerRadius = 5
}
}
#IBOutlet var selectColor: UIButton! {
didSet {
selectColor.layer.cornerRadius = 5
}
}
let transparentView = UIView()
let tableView = UITableView()
var button = UIButton()
var data = [String]()
var searchData = [String]()
var searching : Bool = false
override func viewDidLoad() {
super.viewDidLoad()
tableView.delegate = self
tableView.dataSource = self
tableView.register(Cell.self, forCellReuseIdentifier: "Cell")
searchData = data
}
func addTransparentView(frame : CGRect) {
transparentView.frame = self.view.frame
self.view.addSubview(transparentView)
tableView.frame = CGRect(x: frame.origin.x, y: frame.origin.y + frame.height, width: frame.width, height: 0)
self.view.addSubview(tableView)
tableView.layer.cornerRadius = 5
transparentView.backgroundColor = UIColor.black.withAlphaComponent(0.9)
tableView.reloadData()
let tapgesture = UITapGestureRecognizer(target: self, action: #selector(deleteTransparentView))
transparentView.addGestureRecognizer(tapgesture)
transparentView.alpha = 0
UIView.animate(withDuration: 0.4, delay: 0.0, usingSpringWithDamping: 1.0, initialSpringVelocity: 1.0, options: .curveEaseInOut, animations: {
self.transparentView.alpha = 0.5
self.tableView.frame = CGRect(x: frame.origin.x, y: frame.origin.y + frame.height + 5, width: frame.width, height: CGFloat(self.data.count * 50))
}, completion: nil)
}
#objc func deleteTransparentView() {
let frame = button.frame
UIView.animate(withDuration: 0.4, delay: 0.0, usingSpringWithDamping: 1.0, initialSpringVelocity: 1.0, options: .curveEaseInOut, animations: {
self.transparentView.alpha = 0
self.tableView.frame = CGRect(x: frame.origin.x, y: frame.origin.y + frame.height, width: frame.width, height: 0)
}, completion: nil)
}
#IBAction func selectFruit(_ sender: Any) {
data = ["Apple","Apricots","Avocados","Oranges","Banana","Grapes","Kiwi","JackFruit","Blueberries","Boysenberries"]
button = selectFruit
addTransparentView(frame: selectFruit.frame)
}
#IBAction func selectColor(_ sender: Any) {
data = ["Red","Red1","Red2","Red3","Red4","Purple","Purple1","Purple3","Black","LightGreen","Red5"]
button = selectColor
addTransparentView(frame: selectColor.frame)
}
func searchBar(_ searchBar: UISearchBar, textDidChange textSearched: String) {
if textSearched.isEmpty {
searching = false
searchData.removeAll()
} else {
searching = true
searchData = data.filter{$0.lowercased().contains(textSearched.lowercased())
}
}
tableView.reloadData()
}
// MARK:- TableView Methods
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if searching {
return searchData.count
} else {
return data.count
}
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
if searching {
cell.textLabel?.text = searchData[indexPath.row]
} else {
//Todo: Implement Guard or if here
cell.textLabel?.text = data[indexPath.row]
}
return cell
}
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let searchBar = UISearchBar(frame: CGRect(x: 10, y: 10, width: tableView.frame.width-20, height: 36))
searchBar.searchBarStyle = UISearchBar.Style.prominent
searchBar.placeholder = " Search..."
searchBar.isTranslucent = false
searchBar.delegate = self
return searchBar
}
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 40
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 50
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
button.setTitle(data[indexPath.row], for: .normal)
var buttonTitle = ""
if (searchData.count > 0) {
print("You have searched the fruit \(searchData[indexPath.row])")
buttonTitle = searchData[indexPath.row]
} else {
print("You did not search anyFruit, You just selected \(data[indexPath.row])")
buttonTitle = data[indexPath.row]
}
button.setTitle(buttonTitle, for: .normal)
deleteTransparentView()
}
}
try this one
lazy var searchBar:UISearchBar = UISearchBar()
in viewDidLoad
searchBar.delegate = self
and call this function
func searchBarShouldEndEditing(_ searchBar: UISearchBar) -> Bool {
searchBar.text = ""
return true
}

delete tableviewcell from button within inside the cell

I want my swift code to delete the tableview cell within the cell using the blue button. You can see a example of what I am trying to below in the gif. I also have a indexPath selection var. You should probably have to delete it in the deleteCell func also I assume you would use a tag. All the code is in below no need for storyboard.
import UIKit
class ViewController: UIViewController,UITableViewDelegate,UITableViewDataSource, UIImagePickerControllerDelegate & UINavigationControllerDelegate {
var arr = [1,1,3,3]
var tableview = UITableView()
var selectedIndexPath = IndexPath(row: 0, section: 0)
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 2
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 118
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! customtv
return cell
}
#objc func deleteCell(){
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
tableview.frame = CGRect(x: 0, y: 0, width: view.frame.width, height: view.frame.height * 0.8)
view.addSubview(tableview)
tableview.register(customtv.self, forCellReuseIdentifier: "cell")
tableview.delegate = self
tableview.dataSource = self
}
}
class customtv: UITableViewCell {
lazy var backView : UIView = {
let view = UIView(frame: CGRect(x: 10, y: 6, width: self.frame.width , height: 110))
view.backgroundColor = .green
return view
}()
lazy var btn : UIButton = {
let btn = UIButton(frame: CGRect(x: 50, y: 6, width: 100 , height: 110))
btn.backgroundColor = .blue
return btn
}()
override func layoutSubviews() {
backView.clipsToBounds = true
backView.frame = CGRect(x: 0, y: 6, width: bounds.maxX , height: 110)
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(animated, animated: true)
addSubview(backView)
backView.addSubview(btn)
}
}
Here's my solution:
import UIKit
class ViewController: UIViewController,UITableViewDelegate,UITableViewDataSource, CustomTvCellDelegate, UIImagePickerControllerDelegate & UINavigationControllerDelegate {
var cellCount = 2
var tableview = UITableView()
var selectedIndexPath = IndexPath(row: 0, section: 0)
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return cellCount // use a variable here so you can change it as you delete cells, else it will crash
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 118
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! CustomTv
cell.delegate = self
return cell
}
func deleteCell(_ customTV: CustomTv, location: CGPoint) {
// put the button location in an index path array
var deleteArray = [IndexPath]()
if let indexPath = tableview.indexPathForRow(at: location) {
deleteArray.append(indexPath)
}
cellCount -= 1 // update the row count as you delete a cell
// delete the row using the delete array with a fade animation
tableview.deleteRows(at: deleteArray, with: .fade)
}
override func viewDidLoad() {
super.viewDidLoad()
tableview.frame = CGRect(x: 0, y: 0, width: view.frame.width, height: view.frame.height * 0.8)
view.addSubview(tableview)
tableview.register(CustomTv.self, forCellReuseIdentifier: "cell")
tableview.delegate = self
tableview.dataSource = self
}
}
// you need to declare a cell delegate that will let your tableview know when the button was tapped on the cell
protocol CustomTvCellDelegate: AnyObject {
func deleteCell(_ customTV: CustomTv, location: CGPoint)
}
class CustomTv: UITableViewCell { // it's good form to Pascal case your class name ;)
weak var delegate: CustomTvCellDelegate? // make that delegate a property of your cell
lazy var backView : UIView = {
let view = UIView(frame: CGRect(x: 10, y: 6, width: self.frame.width , height: 110))
view.backgroundColor = .green
return view
}()
lazy var btn : UIButton = {
let btn = UIButton(frame: CGRect(x: 50, y: 6, width: 100 , height: 110))
btn.backgroundColor = .blue
return btn
}()
override func layoutSubviews() {
backView.clipsToBounds = true
backView.frame = CGRect(x: 0, y: 6, width: bounds.maxX , height: 110)
// moved these calls here instead of on setSelected(_selected:animated:)
addSubview(backView)
backView.addSubview(btn)
btn.addTarget(self, action:#selector(self.deleteCell), for: .touchUpInside)
}
#objc func deleteCell(sender: UIButton){
// let your cell delegate (tableview) know what the button got tapped, you need to pass the button here)
let buttonLocation = sender.superview?.convert(sender.frame.origin, to: nil) ?? CGPoint.zero
delegate?.deleteCell(self, location: buttonLocation)
}
}

Adding a Table View Cell when a button is pressed

I want my swift code to add a another tableview cell when the button is pressed. Right now there are 2 tableview cells. The button is the orange button that when pressed should add a 3rd green tabview cell. The func to add the 3rd cell is addCell. Look at numberOfRowsInSelection as well for the area where 2 cells are defined.
import UIKit
class ViewController: UIViewController,UITableViewDelegate,UITableViewDataSource, UIImagePickerControllerDelegate & UINavigationControllerDelegate {
var arr = [1,1,3,3]
var tableview = UITableView()
var arrayThatStartsEmptyImage = [UIImage]()
var currentIndex = 0
var startBtnpress = UIButton()
var selectedIndexPath = IndexPath(row: 0, section: 0)
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 2
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 118
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! customtv
return cell
}
#objc func addCell(){
//add 3 cell
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
tableview.frame = CGRect(x: 0, y: 0, width: view.frame.width, height: view.frame.height * 0.8)
startBtnpress.frame = CGRect(x: 0, y: view.frame.height * 0.8, width: view.frame.width / 2 , height: view.frame.height / 5)
view.addSubview(tableview)
view.addSubview(startBtnpress)
startBtnpress.backgroundColor = .orange
tableview.register(customtv.self, forCellReuseIdentifier: "cell")
tableview.delegate = self
tableview.dataSource = self
}
}
class customtv: UITableViewCell {
lazy var backView : UIView = {
let view = UIView(frame: CGRect(x: 10, y: 6, width: self.frame.width , height: 110))
view.backgroundColor = .green
return view
}()
override func layoutSubviews() {
backView.clipsToBounds = true
backView.frame = CGRect(x: 0, y: 6, width: bounds.maxX , height: 110)
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(animated, animated: true)
addSubview(backView)
}
}
This has been asked a lot before...
Instead of returning a hardcoded value inside tableView(_:numberOfRowsInSection:), you want to return the number of items in your data source (which I'm assuming is arr).
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return arr.count
}
Then, simply add a row with
func addRowToEnd() {
arr.append(5) /// not sure what the numbers mean though...
tableView.beginUpdates()
tableView.insertRows(at: [IndexPath(row: arr.count - 1, section: 0)], with: .automatic) /// animate the insertion
tableView.endUpdates()
}

add together all of the labels in tableview cells

i want my swift code to add together all of the tableview cells together and convert it from a string to a int. The code should be called from the view did load func. The total should be 3 when all of the labels are added together. Look at my comment in view did load for more info. The code does not use storyboards.
import UIKit
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
var numberOfRows = 3
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { numberOfRows }
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { 118 }
var tableView = UITableView()
var selectedIndexPath = IndexPath(row: 0, section: 0)
override func viewDidLoad() {
super.viewDidLoad()
setTableVIew()
//print the sum of the labels added togther on the tableview cells
}
func setTableVIew(){
let VCframe = view.frame
let height = VCframe.height * 0.8
let widthx = VCframe.width
tableView.frame = CGRect(x: 10, y: 0, width: widthx - 20, height: height)
tableView.delegate = self
tableView.dataSource = self
view.addSubview(tableView)
tableView.register(customtv.self, forCellReuseIdentifier: "cell")
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! customtv
cell.lbl.text = "\(indexPath.row)"
return cell
}
}
class customtv: UITableViewCell {
lazy var backView : UIView = {
let view = UIView(frame: CGRect(x: 10, y: 6, width: self.frame.width , height: 110))
view.backgroundColor = .green
print(self.frame.width)
return view
}()
override func layoutSubviews() {
backView.clipsToBounds = true
backView.frame = CGRect(x: 0, y: 6, width: bounds.maxX , height: 110)
}
lazy var lbl : UILabel = {
let press = UILabel(frame: CGRect(x: 0, y: 3, width: 120 , height: 50))
press.backgroundColor = .yellow
press.text = String("1")
return press
}()
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(animated, animated: true)
addSubview(backView)
backView.addSubview(lbl)
}
}
Here's how you do this:
override func viewDidLoad() {
super.viewDidLoad()
setTableView()
calculateSum()
}
func calculateSum() {
var sum = 0
for row in 0..<numberOfRows {
let indexPath = IndexPath(row: row, section: 0)
let cell = tableView.cellForRow(at: indexPath) as! CustomTableViewCell
sum += Int(cell.label.text ?? "") ?? 0
}
print(sum)
}
Note: Make the class and object names consistent eg: lbl -> label and customtv -> CustomTableViewCell as I've given above. Even the method names setTableVIew -> setTableView. It would be best if you use SwiftLint.

iOS11 how to sync large navigation bar collapse with scroll

Using Swift 3 with Xcode 9 I'm using the large UINavigationBar view by:
if #available(iOS 11.0, *) {
navigationBar?.prefersLargeTitles = true
UINavigationBar.appearance().largeTitleTextAttributes = [
NSForegroundColorAttributeName: Colors.black
]
}
When I scroll a UITableView, the bar collapses too fast which creates an unwanted space:
Before:
After:
The moment I touch the UITableView the bar collapses.
The tableView has the following properties:
let rect = CGRect(
x: 0,
y: UIApplication.shared.statusBarView?.frame.height ?? 20,
width: UIScreen.main.bounds.width,
height: UIScreen.main.bounds.height
)
let tableView = UITableView(frame: rect)
The top inset of the tableView is self.navigationController?.navigationBar.frame.height ?? 44
Also the tableView is set to:
if #available(iOS 11.0, *) {
self.contentInsetAdjustmentBehavior = .never
}
The bar is translucent and I wish to keep that. What am I missing? Help is very appreciated.
I don't know whether it will useful to you or not. But its the sample code which is working for me.
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, UISearchResultsUpdating {
var numbers: [String] = []
let rect = CGRect(
x: 0,
y: UIApplication.shared.statusBarFrame.height ?? 20,
width: UIScreen.main.bounds.width,
height: UIScreen.main.bounds.height
)
lazy var tableView: UITableView = {
let tV = UITableView()
tV.delegate = self
tV.dataSource = self
tV.register(UITableViewCell.classForCoder(), forCellReuseIdentifier: "cell")
return tV
}()
override func viewDidLoad() {
super.viewDidLoad()
numbers = generateNumbers()
self.view.backgroundColor = UIColor.white
title = "Numbers"
self.navigationController?.navigationBar.prefersLargeTitles = true
let search = UISearchController(searchResultsController: nil)
search.hidesNavigationBarDuringPresentation = false
search.searchResultsUpdater = self
search.definesPresentationContext = true
self.navigationItem.searchController = search
tableView.frame = rect
self.view.addSubview(tableView)
}
func generateNumbers() -> [String] {
var numbers = [String]()
for var i in 1..<100 {
numbers.append(String(i))
}
return numbers
}
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return numbers.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
cell.textLabel?.text = self.numbers[indexPath.row]
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
}
func updateSearchResults(for searchController: UISearchController) {
if let text = searchController.searchBar.text, !text.isEmpty {
numbers = self.numbers.filter({ (number) -> Bool in
return number.contains(text)
})
} else {
numbers = generateNumbers()
}
self.table.reloadData()
}
}
I got it working using:
if #available(iOS 11.0, *) {
self.contentInsetAdjustmentBehavior = .always
}
And
let tableViewFrame = CGRect(
x: 0,
y: UIApplication.shared.statusBarFrame.height ?? 20,
width: UIScreen.main.bounds.width,
height: UIScreen.main.bounds.height
)
And no further TableView top insets.