How I can pin the tableHeaderView? - swift

Tell me, please, how I can pin the tableHeaderView on the ViewController's screen through code? I use this code, but the tableViewHeader disappears on scrolling:
import UIKit
class TestViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
lazy var tableViewTest = UITableView()
override func viewDidLoad() {
super.viewDidLoad()
createTable()
}
private func createTable() {
self.tableViewTest = UITableView(frame: view.bounds, style: .grouped)
tableViewTest.register(TestTableViewCell.self, forCellReuseIdentifier: "Test")
self.tableViewTest.delegate = self
self.tableViewTest.dataSource = self
tableViewTest.autoresizingMask = [.flexibleWidth, .flexibleHeight]
tableViewTest.separatorInset.left = 10
tableViewTest.separatorInset.right = 10
tableViewTest.tableHeaderView = "Test Header"
view.addSubview(tableViewTest)
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 10
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Test", for: indexPath) as! TestTableViewCell
cell.testLabel.text = "test label"
return cell
}
}
This is my second class:
import UIKit
class TestTableViewCell: UITableViewCell {
let testLabel = UILabel()
override func layoutSubviews() {
super.layoutSubviews()
testLabel.frame = CGRect(x: 60, y: 5, width: UIScreen.main.bounds.width - 80, height: 50)
testLabel.numberOfLines = 0
testLabel.sizeToFit()
addSubview(testLabel)
}
override func awakeFromNib() {
super.awakeFromNib()
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
}
}

Try to use the implicit construct of UITableView
lazy var tableViewTest = UITableView(frame: .zero, style: .plain)
But also you need to change your table header to section header which you can define in UITableViewDelegate method
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let identifier = YourSectionHeaderView.reuseIdentifier
let headerView =
tableView.dequeueReusableHeaderFooterView(withIdentifier: identifier)
return headerView
}
By the way, I also recommend you to use constraint instead of autoresizing mask

Thank you.
This work for me:
import UIKit
class TestViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
lazy var tableViewTest = UITableView()
var segmentedControl = UISegmentedControl(items: ["Test1", "Test2", "Test3"])
override func viewDidLoad() {
super.viewDidLoad()
createTable()
configureSegmentedControl()
}
private func createTable() {
self.tableViewTest = UITableView(frame: view.bounds, style: .plain)
tableViewTest.register(TestTableViewCell.self, forCellReuseIdentifier: "Test")
self.tableViewTest.delegate = self
self.tableViewTest.dataSource = self
tableViewTest.autoresizingMask = [.flexibleWidth, .flexibleHeight]
tableViewTest.separatorInset.left = 10
tableViewTest.separatorInset.right = 10
tableViewTest.tableFooterView = UIView()
view.addSubview(tableViewTest)
}
private func configureSegmentedControl() {
segmentedControl.selectedSegmentIndex = 0
segmentedControl.frame = CGRect(x: 10, y: 150, width: UIScreen.main.bounds.width - 20.0, height: 40)
segmentedControl.layer.cornerRadius = 5.0
segmentedControl.backgroundColor = .blue
segmentedControl.selectedSegmentTintColor = .red
segmentedControl.tintColor = .white
segmentedControl.addTarget(self, action: #selector(changeSegment), for: .valueChanged)
}
#objc func changeSegment(sender: UISegmentedControl) {
switch sender.selectedSegmentIndex {
case 0:
print("Test1")
case 1:
print("Test2")
default:
print("Test3")
}
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 10
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Test", for: indexPath) as! TestTableViewCell
cell.testLabel.text = "test label"
return cell
}
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
return segmentedControl
}
}

Related

What is this extra row in the UITabBar (Swift)

I programmatically add a TableView in a ViewController, then appeared an extra row. I would like to be able to manage it, but first I would have to know what it is. This line seems to come from the TabBar rather than the TableView. Do you know which object it is?
The code:
import UIKit
final class SearchViewController2: UIViewController, UITableViewDataSource, UITableViewDelegate {
private let ingredients = [
"flour",
"sugar",
"eggs",
"butter",
"baking powder",
"vanilla extract",
"milk",
"salt",
"cocoa powder",
"yeast",
"olive oil",
"cheese",
"breadcrumbs",
"onions",
"garlic",
"tomatoes",
"basil",
"oregano",
"thyme",
"parsley",
"pepper"
]
private let tableView: UITableView = {
let tableView = UITableView()
tableView.register(UITableViewCell.self, forCellReuseIdentifier: "cell")
return tableView
}()
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
let ingredient = ingredients[indexPath.row]
var cellConfig = cell.defaultContentConfiguration()
cellConfig.text = ingredient
cell.contentConfiguration = cellConfig
return cell
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
ingredients.count
}
override func viewDidLoad() {
super.viewDidLoad()
let header = StretchyTableHeaderView(
frame: CGRect(
x: 0,
y: 0,
width: view.frame.size.width,
height: view.frame.size.width / 2
)
)
view.addSubview(tableView)
header.imageView.image = UIImage(named: "header")
tableView.dataSource = self
tableView.delegate = self
tableView.frame = view.bounds
tableView.tableHeaderView = header
}
}
extension SearchViewController2: UIScrollViewDelegate {
func scrollViewDidScroll(_ scrollView: UIScrollView) {
guard let header = tableView.tableHeaderView as? StretchyTableHeaderView else { return }
header.scrollViewDidScroll(scrollView: tableView)
}
}
I tried to add/remove a footer in the TableView... No changes.

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.

Adding two UITableViews in one UIVIewController programmatically and want to change the View of Controller with UISegmentedControl

I want to change the View of my ViewController based on 2 tableVIews with segmentedControl. I have reached it with programmatic approach. I created two TableViews and One SegmentedControl. But When I change the segmentedControl it stays on the same Index but changing the View. I have to tap twice on each Segment to reach it. Why it is happening?
Here is my code:
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
configureFirstTableView()
}
var firstTableView = UITableView()
var secondTableView = UITableView()
func configureFirstTableView() {
firstTableView.frame = self.view.frame
firstTableView.delegate = self
firstTableView.dataSource = self
firstTableView.register(UITableViewCell.self, forCellReuseIdentifier: "FirstCell")
view.addSubview(firstTableView)
}
func configureSecondTableView() {
secondTableView.frame = self.view.frame
secondTableView.delegate = self
secondTableView.dataSource = self
secondTableView.register(UITableViewCell.self, forCellReuseIdentifier: "SecondCell")
view.addSubview(secondTableView)
}
func configureSegmentedControl() -> UISegmentedControl {
let segmentedControl = UISegmentedControl(frame: CGRect(x: 10, y: 5, width: view.frame.width - 10, height: 30))
segmentedControl.insertSegment(withTitle: "First", at: 0, animated: false)
segmentedControl.insertSegment(withTitle: "Second", at: 1, animated: false)
segmentedControl.selectedSegmentIndex = 0
segmentedControl.addTarget(self, action: #selector(changeSegmentedControlValue(_:)), for: .valueChanged)
return segmentedControl
}
#objc func changeSegmentedControlValue(_ sender: UISegmentedControl) {
switch sender.selectedSegmentIndex {
case 0:
print("1")
configureFirstTableView()
case 1:
print("2")
configureSecondTableView()
default:
break
}
}
}
extension ViewController: UITableViewDelegate, UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
var count: Int?
if tableView == firstTableView {
count = 3
return count!
} else if tableView == secondTableView {
count = 4
return count!
}
return count!
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if tableView == firstTableView {
let cell = tableView.dequeueReusableCell(withIdentifier: "FirstCell", for: indexPath)
cell.textLabel?.text = "First"
return cell
} else if tableView == secondTableView {
let cell = tableView.dequeueReusableCell(withIdentifier: "SecondCell", for: indexPath)
cell.textLabel?.text = "Second"
return cell
}
return UITableViewCell()
}
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let v = UIView()
v.backgroundColor = .white
v.addSubview(configureSegmentedControl())
return v
}
}

didDiscoverPeripheral never called in Swift [duplicate]

Can anyone see why in the world didSelectRowAtIndexPath would not be called? I have triple checked by delegate both in the code and in storyboard.
class AddCard: UIViewController,UIPopoverPresentationControllerDelegate, UITableViewDataSource, UITableViewDelegate {
#IBOutlet weak var cardView: UIView!
#IBOutlet weak var tableView: UITableView!
let tableItems = ["Background Color","Background Image","Font Style","Font Color"]
let cellID = "cell"
override func viewDidLoad() {
super.viewDidLoad()
tableView.delegate = self
tableView.dataSource = self
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func setBackgroundColor (_ color: UIColor) {
cardView.backgroundColor = color
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return tableItems.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: cellID, for: indexPath as IndexPath)
let row = indexPath.row
cell.textLabel?.text = tableItems[row]
return cell
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: IndexPath) {
tableView.deselectRow(at: indexPath as IndexPath, animated: true)
print(indexPath.row)
let row = indexPath.row
switch(row){
case 0:
let popoverVC = storyboard?.instantiateViewController(withIdentifier: "colorPickerVC") as! ColorPickerViewController
popoverVC.modalPresentationStyle = .popover
popoverVC.preferredContentSize = CGSize(width: 284, height: 446)
if let popoverController = popoverVC.popoverPresentationController {
popoverController.sourceView = self.view
popoverController.sourceRect = CGRect(x: 0, y: 0, width: 85, height: 30)
popoverController.permittedArrowDirections = .any
popoverController.delegate = self
popoverVC.delegate = self
}
present(popoverVC, animated: true, completion: nil)
break
default: break
}
}
}
Swift 3 modified the signature of the method (a lot of methods too, new "rules"/style)
Replace:
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: IndexPath) with
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath)
Notice the _, the didSelectRowAt vs didSelectRowAtIndexPath, like the other ones you updated (which adapted also the same "style"), but not this one.
Remove the line and let XCode do the autocompletion. Else, you can just replace it with the one from the doc.

Swift side bar menu complies but does not appear

I have been to following this guide [https://www.youtube.com/watch?v=qaLiZgUK2T0] for the creation of a swift sidebar menu: The code compiles, with out errors... I must be missing something simple somewhere....The menu does not appear. Please assist me with locating this issue.
The code for the menu is listed below in three files:
ViewController.swift:
import UIKit
class ViewController: UIViewController, SideBarDelegate {
var sideBar:SideBar = SideBar()
override func viewDidLoad() {
super.viewDidLoad()
sideBar = SideBar(sourceView: self.view, menuItems: ["first item","second item","third item"])
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func sideBarDidSelectButtonAtIndex(index: Int) {
}
}
SideBarTableViewController.swift:
import UIKit
protocol SideBarTableViewControllerDelegate{
func sideBarControlDidSelectRow(indexPath:NSIndexPath);
}
class SideBarTableViewController: UITableViewController {
var delegate:SideBarTableViewControllerDelegate?
var tableData:Array<String> = []
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return tableData.count;
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell:UITableViewCell? = tableView.dequeueReusableCellWithIdentifier("Cell") as? UITableViewCell
if cell == nil{
cell = UITableViewCell(style :UITableViewCellStyle.Default, reuseIdentifier: "Cell")
// Configure the cell...
cell!.backgroundColor = UIColor.clearColor()
cell!.textLabel.textColor = UIColor.darkTextColor()
let selectedView:UIView = UIView(frame: CGRect (x: 0, y:0, width: cell!.frame.size.width, height: cell!.frame.size.height))
selectedView.backgroundColor = UIColor.blackColor().colorWithAlphaComponent(0.3)
cell!.selectedBackgroundView = selectedView
}
cell!.textLabel.text = tableData[indexPath.row]
return cell!
}
override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat{
return 45.0
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
delegate?.sideBarControlDidSelectRow(indexPath)
}
}
SideBar.swift
import UIKit
#objc protocol SideBarDelegate{
func sideBarDidSelectButtonAtIndex(index:Int)
optional func sideBarWillClose()
optional func sideBarWillOpen()
}
class SideBar: NSObject, SideBarTableViewControllerDelegate {
let barWidth : CGFloat = 150;
let sideBarTableViewTopInset:CGFloat = 64.0;
let sideBarContainerView: UIView = UIView()
let sideBarTableViewController: SideBarTableViewController = SideBarTableViewController()
let orginView : UIView!
var animator: UIDynamicAnimator!
var delegate:SideBarDelegate?
var isSideBarOpen:Bool = false
override init(){
super.init()
}
init(sourceView: UIView, menuItems:Array<String>){
super.init()
orginView = sourceView
sideBarTableViewController.tableData = menuItems
animator = UIDynamicAnimator(referenceView: orginView)
let showGestureRecognizer:UISwipeGestureRecognizer = UISwipeGestureRecognizer(target: self, action: "handleSwipe:")
showGestureRecognizer.direction = UISwipeGestureRecognizerDirection.Right
orginView.addGestureRecognizer(showGestureRecognizer)
let hideGesturerecognizer:UISwipeGestureRecognizer = UISwipeGestureRecognizer(target: self, action: "handleSwipe:")
hideGesturerecognizer.direction = UISwipeGestureRecognizerDirection.Left
orginView.addGestureRecognizer(hideGesturerecognizer)
}
func setupSideBar(){
sideBarContainerView.frame = CGRectMake(-barWidth - 1,orginView.frame.origin.y, barWidth, orginView.frame.size.height)
sideBarContainerView.backgroundColor = UIColor.clearColor()
sideBarContainerView.clipsToBounds = false
orginView.addSubview(sideBarContainerView)
let blurView:UIVisualEffectView = UIVisualEffectView(effect:
UIBlurEffect(style: UIBlurEffectStyle.Light))
blurView.frame = sideBarContainerView.bounds
sideBarContainerView.addSubview(blurView)
sideBarTableViewController.delegate = self
sideBarTableViewController.tableView.frame = sideBarContainerView.bounds
sideBarTableViewController.tableView.clipsToBounds = false
sideBarTableViewController.tableView.separatorStyle = UITableViewCellSeparatorStyle.None
sideBarContainerView.backgroundColor = UIColor.clearColor()
sideBarTableViewController.tableView.scrollsToTop = false
sideBarTableViewController.tableView.contentInset = UIEdgeInsetsMake(sideBarTableViewTopInset, 0,0,0)
sideBarTableViewController.tableView.reloadData()
sideBarContainerView.addSubview(sideBarTableViewController.tableView)
}
func handleSwipe(recognizer:UISwipeGestureRecognizer){
if (recognizer.direction == UISwipeGestureRecognizerDirection.Left){
showSideBar(false)
delegate?.sideBarWillClose?()
}else{
showSideBar(true)
delegate?.sideBarWillClose?()
}
}
func showSideBar(shouldOpen:Bool){
animator.removeAllBehaviors()
isSideBarOpen = shouldOpen
let gravityX:CGFloat = (shouldOpen) ? 0.5 : -0.5
let magnitude:CGFloat = (shouldOpen) ? 20 : -20
let boundryX: CGFloat = (shouldOpen) ? barWidth : -barWidth - 1
let gravityBehavior:UIGravityBehavior = UIGravityBehavior(items: [sideBarContainerView])
gravityBehavior.gravityDirection = CGVectorMake(gravityX, 0)
let collisonBehavior:UICollisionBehavior = UICollisionBehavior(items: [sideBarContainerView])
collisonBehavior.addBoundaryWithIdentifier("sideBarBoundary", fromPoint: CGPointMake(boundryX, 20), toPoint: CGPointMake(boundryX, orginView.frame.size.height))
animator.addBehavior(collisonBehavior)
let pushBehavior:UIPushBehavior = UIPushBehavior(items: [sideBarContainerView], mode: UIPushBehaviorMode.Instantaneous)
animator.addBehavior(pushBehavior)
let sideBarBehavior:UIDynamicItemBehavior = UIDynamicItemBehavior(items: [sideBarContainerView])
sideBarBehavior.elasticity = 0.3
animator.addBehavior(sideBarBehavior)
}
func sideBarControlDidSelectRow(indexPath: NSIndexPath) {
delegate?.sideBarDidSelectButtonAtIndex(indexPath.row)
}
}
I went through and debugged the project file when you download the source code and all I had to do to get it to work was make a bunch of minor changes to the SideBarTableViewController.swift and everything worked for me. Here it is:
import UIKit
protocol SideBarTableViewControllerDelegate{
func sideBarControlDidSelectRow(indexPath:NSIndexPath)
}
class SideBarTableViewController: UITableViewController {
var delegate:SideBarTableViewControllerDelegate?
var tableData:Array<String> = []
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return tableData.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell = tableView.dequeueReusableCellWithIdentifier("Cell") as? UITableViewCell
if cell == nil{
cell = UITableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: "Cell")
// Configure the cell...
cell?.backgroundColor = UIColor.clearColor()
cell?.textLabel?.textColor = UIColor.darkTextColor()
let selectedView:UIView = UIView(frame: CGRect(x: 0, y: 0, width: cell!.frame.size.width, height: cell!.frame.size.height))
selectedView.backgroundColor = UIColor.blackColor().colorWithAlphaComponent(0.3)
cell!.selectedBackgroundView = selectedView
}
cell?.textLabel?.text = tableData[indexPath.row]
return cell!
}
override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return 45.0
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
delegate?.sideBarControlDidSelectRow(indexPath)
}
}