How to create expandable tableview in swift

1. Using Pod

pod ‘LUExpandableTableView’

2. Manually

drag and drop from LUExpandableTableView

1.LUExpandableTableViewDataSource.swift
2.LUExpandableTableView.h
3.LUExpandableTableView.swift
4.LUExpandableTableViewDelegate.swift
5.LUExpandableTableViewSectionHeader.swift
Create xib for header of tableview

import UIKit

class ViewController: UIViewController {

private let sectionHeaderReuseIdentifier = "MySectionHeader"
@IBOutlet weak var tableview: LUExpandableTableView!
override func viewDidLoad() {
super.viewDidLoad()

tableview.register(UINib(nibName: "MyExpandableTableViewSectionHeader", bundle: Bundle.main), forHeaderFooterViewReuseIdentifier: sectionHeaderReuseIdentifier)

tableview.expandableTableViewDataSource = self
tableview.expandableTableViewDelegate = self

}
}

extension ViewController: LUExpandableTableViewDataSource {
func numberOfSections(in expandableTableView: LUExpandableTableView) -> Int {
return 10
}

func expandableTableView(_ expandableTableView: LUExpandableTableView, numberOfRowsInSection section: Int) -> Int {
return 5
}

func expandableTableView(_ expandableTableView: LUExpandableTableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

guard let cell = expandableTableView.dequeueReusableCell(withIdentifier: "cell") as? ExpTableViewCell else {
assertionFailure("Cell shouldn't be nil")
return UITableViewCell()
}

cell.mylabel.text = "Cell at row \(indexPath.row) section \(indexPath.section)"

return cell
}

func expandableTableView(_ expandableTableView: LUExpandableTableView, sectionHeaderOfSection section: Int) -> LUExpandableTableViewSectionHeader {
guard let sectionHeader = tableview.dequeueReusableHeaderFooterView(withIdentifier: sectionHeaderReuseIdentifier) as? MyExpandableTableViewSectionHeader else {
assertionFailure("Section header shouldn't be nil")
return LUExpandableTableViewSectionHeader()
}

sectionHeader.label.text = "Section \(section)"
return sectionHeader
}
}

// MARK: - LUExpandableTableViewDelegate
extension ViewController: LUExpandableTableViewDelegate {
func expandableTableView(_ expandableTableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
return 0
}

func expandableTableView(_ expandableTableView: LUExpandableTableView, heightForRowAt indexPath: IndexPath) -> CGFloat {

return 50
}

func expandableTableView(_ expandableTableView: LUExpandableTableView, heightForHeaderInSection section: Int) -> CGFloat {
return 60
}

// MARK: - Optional

func expandableTableView(_ expandableTableView: LUExpandableTableView, didSelectRowAt indexPath: IndexPath) {
print("Did select cell at section \(indexPath.section) row \(indexPath.row)")
}

func expandableTableView(_ expandableTableView: LUExpandableTableView, didSelectSectionHeader sectionHeader: LUExpandableTableViewSectionHeader, atSection section: Int) {
print("Did select cection header at section \(section)")
}

func expandableTableView(_ expandableTableView: LUExpandableTableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
print("Will display cell at section \(indexPath.section) row \(indexPath.row)")
}

func expandableTableView(_ expandableTableView: LUExpandableTableView, willDisplaySectionHeader sectionHeader: LUExpandableTableViewSectionHeader, forSection section: Int) {
print("Will display section header for section \(section)")
}
}

TABLEVIEW CELL

class ExpTableViewCell: UITableViewCell {

@IBOutlet weak var mylabel: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}

override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)

// Configure the view for the selected state
}

}

CREATE CLASS FOR HEADER

import UIKit

final class MyExpandableTableViewSectionHeader: LUExpandableTableViewSectionHeader {
// MARK: - Properties

@IBOutlet weak var expandCollapseButton: UIButton!
@IBOutlet weak var label: UILabel!

override var isExpanded: Bool {
didSet {
// Change the title of the button when section header expand/collapse
expandCollapseButton?.setTitle(isExpanded ? "Less" : "More", for: .normal)
}
}

// MARK: - Base Class Overrides

override func awakeFromNib() {
super.awakeFromNib()

label?.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(didTapOnLabel)))
label?.isUserInteractionEnabled = true
}

// MARK: - IBActions

@IBAction func expandCollapse(_ sender: UIButton) {
// Send the message to his delegate that shold expand or collapse
delegate?.expandableSectionHeader(self, shouldExpandOrCollapseAtSection: section)
}

// MARK: - Private Functions

@objc private func didTapOnLabel(_ sender: UIGestureRecognizer) {
// Send the message to his delegate that was selected
delegate?.expandableSectionHeader(self, wasSelectedAtSection: section)
}
}

Different between Swift and objective C

Objective C

-> Objective-C is a pure superset of C.
-> structs, enums, and scalar types of objects are not supported in Objective C.
-> Objective C Does not support tuple.
-> Objective C is not support optional.
-> lower compile time compare to swift
-> Objective C have header and implementation file.
-> Objective C is easily compatible with C++
-> Objective C is hard to learn compare to swift.

Swift

->Swift is a more modern language
-> structs, enums, and scalar types of objects are supported in Swift.
-> Swift supports Tuples.
-> Swift is support optional and optional chaining
-> Higher compile time.
-> Swift have only one file contains both interface
-> Swift C is not compatible with C++
-> Swift is more readable and less code programming language

How to remove or filter specific elements from array in swift

let YourArr = ["one", "two", "three", "four"]

First way to remove element from array in swift

let result = YourArr.filter { $0 != "one" }
OUTPUT : ["two", "three", "four"]

Second way to remove element using specific index from array

YourArr.remove(at: 0)
OUTPUT : ["two", "three", "four"]

Note : If you do not have index then get index from array like this

let index = YourArr.indexOf("one") //OUTPUT : 0
let index = YourArr.indexOf("two") //OUTPUT : 1

YourArr.remove(at: index)

How can addition of whole element of array in swift

We can addition of element using reduce function in swift

let addition = [1,2,3,4,5]
let sum = addition.reduce(0, +)
print("Sum of Element is : ", sum)

how can i get number from string array in swift using compactMap

let numbers = ["1", "2", "one", "two"]

let string = numbers.compactMap { String($0) }
print(string)
//OUTPUT ["1", "2", "one", "two"]

let integer = numbers.compactMap { Int($0) }
print(integer)
//OUTPUT [1, 2]
print(integers)

how to post on facebook and twitter in swift

You can Post quotes or url in facebook or twitter in swift using social framework.

POST ON FACEBBOK

import Social

let controller = SLComposeViewController(forServiceType: SLServiceTypeFacebook)

controller?.add(URL(string: "your url")) controller?.setInitialText(MarketingContent)
present(controller!, animated: true)

POST ON TWITTER

import Social

let controller = SLComposeViewController(forServiceType: SLServiceTypeTwitter)

controller?.add(URL(string: "your url")) controller?.setInitialText(MarketingContent)
present(controller!, animated: true)

How to Send Mail Using MFMailComposeViewController in swift


if MFMailComposeViewController.canSendMail() {
let mail = MFMailComposeViewController()
mail.mailComposeDelegate = self
mail.setToRecipients(["Your Email Address here"])
mail.setMessageBody("





Product: App Name \r
Device: \(UIDevice.current.name) \r
Model: \(UIDevice.current.model) \r
iOS Version: \(UIDevice.current.systemVersion) \r
" , isHTML: true)

present(mail, animated: true
} else {
print("Something went wrong")
}

DELEGATE METHOD

func mailComposeController(_ controller: MFMailComposeViewController, didFinishWith result: MFMailComposeResult, error: Error?) {

switch result {
case .failed:
print("failed")
controller.dismiss(animated: true)

case .sent:
print("Sent")

default:
print("default")
}

}