how to instantiate ViewController from UIView in SWIFT - ios

I am trying to initialize view controller from my UiView. But i am getting error on the line self.presentViewController(vc, animated: true, completion: nil) . I am trying to show another view controller after click on a table row. i have already initialized storyboard.
import UIKit
class CustomSwipeOut: UIView , UITableViewDataSource , UITableViewDelegate {
var label: UILabel = UILabel()
var myNames = ["item1","item2","item3"]
override init(frame: CGRect) {
super.init(frame: frame)
self.addCustomView()
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func addCustomView()
{
//add blank subview to the view
var blankView : UIView = UIView(frame: CGRectMake(0, 0, 300, 100))
blankView.backgroundColor = UIColor.greenColor()
self.addSubview(blankView)
//creating a tableview programmatically
var tblView : UITableView = UITableView()
tblView.frame = CGRectMake(0, 100, 300, 200)
self.addSubview(tblView)
tblView.delegate = self
tblView.dataSource = self
tblView.registerClass(UITableViewCell.self, forCellReuseIdentifier: "myCell")
}
//pragma mark- table view data source methods
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell : UITableViewCell = tableView.dequeueReusableCellWithIdentifier("myCell") as UITableViewCell
cell.textLabel?.text = self.myNames[indexPath.row]
return cell
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.myNames.count
}
//pragma mark - table view delegate methods
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
switch indexPath.row {
case 0:
println("index o clicked")
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let vc = storyboard.instantiateViewControllerWithIdentifier("MoneySum") as UIViewController
self.presentViewController(vc, animated: true, completion: nil)
case 1:
println("index 1 clicked")
case 2:
println("index 2 clicked")
default:
println("no index")
}
}
}

presentViewController:animated:completion: is a method defined only for UIViewController, not UIView (see Apple doc here).
Your UIView is probably in the view hierarchy managed by a UIViewController.
A solution would be using a reference to that parent UIViewController and invoking presentViewController:animated:completion: on it.

However..i accomplised using a delegate to pass an id from UIView to UIViewController and checking to the id i instantiated ViewController From UIViewController class as Para said in his answer . I did it as below
Steps:
1) First create a protocol
2) create a Variable delegate conforming to protocol
3)Then create a call back method.
//Step1:
protocol SendIndexDelegate{
func sendIndex(Int);
}
class CustomSwipeView: UIView , UITableViewDataSource , UITableViewDelegate {
var delegate : SendIndexDelegate? //Step2
override init(frame: CGRect) {
super.init(frame: frame)
self.addCustomView()
}
......
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
var row = indexPath.row
//for optional binding
if let temp = self.delegate {
delegate?.sendIndex(row) //Step 3
}else{
println("optional value contains nill value")
}
}
}
Steps Continued for Another Class:
4) Conform to the protocol SendIndexDelegate(so method sendIndex(Int) must be impelemented by this class)
5) Assign the value self in variable delegate in the optional variable delegate(it says that i will act as delegate for Class CustomSwipeView and implement the method sendIndex(Int))
6) Now implement the method and add body to it(because it has been delegate so must handle actions of the above class through call back method)
class RootViewController: UIViewController,SendIndexDelegate //Step4 {
let rect: CGRect = CGRect (x: self.view.frame.size.width, y :10 , width: self.view.frame.size.width-50, height: self.view.frame.size.height-10)
var a = CustomSwipeView(frame : rect)
a.delegate = self//step5
self.myView = a
self.view.addSubview(self.myView)
}
// Step 6:
func sendIndex(row : Int){
switch row {
case 0:
let storyboard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
let moneySummaryVC: MoneySummaryVC = storyboard.instantiateViewControllerWithIdentifier("moneyVC") as! MoneySummaryVC
self.navigationController?.pushViewController(moneySummaryVC, animated: true)
default:
println("no index")
}
}

You can use window to present any ViewController from your UIView Class. See this answer: https://stackoverflow.com/a/75396813/7385095

Related

Testing the presented UITableViewCell in a UITableView

I'm testing a simple tableView in a UIViewController for fun
class ViewController: UIViewController {
#IBOutlet weak var tableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
setup()
}
func setup() {
tableView.dataSource = self
tableView.delegate = self
tableView.register(CustomTableViewCell.self, forCellReuseIdentifier: "CustomTableViewCell")
}
var data = [1,2,3,4,5,6,7]
}
extension ViewController : UITableViewDelegate {
}
extension ViewController : UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return data.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "CustomTableViewCell", for: indexPath)
cell.textLabel?.text = data[indexPath.row].description
return cell
}
}
and I want to write a test to check that the correct data is being displayed in a presented cell.
My test looks like the following:
var controller: ViewController?
override func setUp() {
controller = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "ViewController") as? ViewController
}
func testViewCell() {
guard let controller = controller else {
return XCTFail("Could not instantiate ViewController")
}
let tableCell = Bundle(for: CustomTableViewCell.self).loadNibNamed("CustomTableViewCell", owner: nil)?.first as! CustomTableViewCell
tableCell.textLabel?.text = "2"
controller.loadViewIfNeeded()
let actualCell = controller.tableView!.cellForRow(at: IndexPath(row: 0, section: 0) )
XCTAssertEqual(actualCell, tableCell)
}
But the actual cell is nil. How can I test the presented cell in my view controller against an expected cell?
In your case I believe you will need to call reloadData on the table view as well. Try:
func testViewCell() {
guard let controller = controller else {
return XCTFail("Could not instantiate ViewController")
}
let tableCell = Bundle(for: CustomTableViewCell.self).loadNibNamed("CustomTableViewCell", owner: nil)?.first as! CustomTableViewCell
tableCell.textLabel?.text = "2"
controller.loadViewIfNeeded()
controller.tableView!.reloadData()
let actualCell = controller.tableView!.cellForRow(at: IndexPath(row: 0, section: 0) )
XCTAssertEqual(actualCell, tableCell)
}
In general for these cases I would also be worried about the view controller size. Since this is not put to any window it might in some cases use some intrinsic size and if that is for instance set to 0 your cells will not be there either. Maybe you should consider creating a window with fixed size (the size you want to test on) and apply your view controller as a root to it.
Also what do you expect to get from XCTAssertEqual(actualCell, tableCell)? Not sure but I would say this tests only pointers and will always fail. You will need to implement your own logic to check equality.

Using custom XIB in table view cell

I have followed this tutorial to create a custom .xib, which I plan to use in a table view's cell:
https://medium.com/#brianclouser/swift-3-creating-a-custom-view-from-a-xib-ecdfe5b3a960
Here is the .xib's class I created:
class UserView: UIView {
#IBOutlet var view: UIView!
#IBOutlet weak var username: UILabel!
override init(frame: CGRect) {
super.init(frame: frame)
initialize()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
initialize()
}
private func initialize() {
Bundle.main.loadNibNamed("UserView", owner: self, options: nil)
addSubview(view)
view.frame = self.bounds
view.autoresizingMask = [.flexibleHeight, .flexibleWidth]
}
}
Previously, I was creating my table view cell within the storyboard, but I've come to realize that I want a more flexible view so that I can use it in different parts of my app, so I created the above custom .xib, UserView.
I have updated the table view cell in the storyboard to use the custom .xib:
https://i.stack.imgur.com/t7Tr7.png
Here is what my table view controller class looked like prior to creating the custom .xib (i.e. making the layout in the storyboard):
class UserTableViewController: UITableViewController {
// MARK: Properties
let provider = MoyaProvider<ApiService>()
var users = [User]()
override func viewDidLoad() {
super.viewDidLoad()
tableView.estimatedRowHeight = 100
tableView.rowHeight = UITableViewAutomaticDimension
// Fetch the user by their username
provider.request(.getUsers()) { result in
switch result {
case let .success(response):
do {
let results = try JSONDecoder().decode(Pagination<[User]>.self, from: response.data)
self.users.append(contentsOf: results.data)
self.tableView.reloadData()
} catch {
print(error)
}
case let .failure(error):
print(error)
break
}
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return users.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cellIdentifier = "UserTableViewCell"
guard let cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier, for: indexPath) as? UserTableViewCell else {
fatalError("The dequeued cell is not an instance of UserTableViewCell.")
}
let user = users[indexPath.row]
cell.username.text = user.username
return cell
}
}
Here is the table view cell class:
class UserTableViewCell: UITableViewCell {
//MARK: Properties
#IBOutlet weak var userView: UserView!
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
}
}
My question is, how do I update the above table view controller class to use my custom .xib, instead of using the storyboard layout?
You can use 2 ways:
Create UITableViewCell (better)
1) Change UIView to UITableViewCell
class CustomTableViewCell: UITableViewCell {
...
class var identifier: String {
return String(describing: self)
}
}
2) Register your cell
override func viewDidLoad() {
super.viewDidLoad()
self.tableView.registerNib(UINib(nibName: CustomTableViewCell.identifier, bundle: nil), forCellReuseIdentifier: CustomTableViewCell.identifier)
...
}
3) Use cellForRow(at:)
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: CustomTableViewCell.identifier) as! CustomTableViewCell
cell.username.text = user.username
return cell
}
OR Add view as subview to cell (only in rare cases)
1) Add this to UserView
class UserView: UIView {
...
class func fromNib() -> UserView {
return UINib(nibName: String(describing: self), bundle: nil).instantiate(withOwner: nil, options: nil)[0] as! UserView
}
}
2) Use cellForRow(at:)
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cellIdentifier = "UserTableViewCell"
guard let cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier, for: indexPath) as? UserTableViewCell else {
fatalError("The dequeued cell is not an instance of UserTableViewCell.")
}
let userView = UserView.fromNib()
let user = users[indexPath.row]
userView.username.text = user.username
//Use frame size, but for me better to add 4 constraints
userView.frame = CGRect(x: 0, y: 0, width: cellWidth, height: cellHeight)
cell.contentView.addSubview(UserView)
return cell
}

create UICollectionViewController subclass and add as a childviewcontroller

I am new to iOS development. I want to create collectionView in two different view controllers with same UI.I want to create only one UICollectionView and resuse it on different view controller instead of create separate collectionViews . On approach i can follow is to create the UICollectionViewController subclass and add this on my viewcontrollers as a childviewcontroller, but not sure if this is the correct approach do not know how addChildViewcontroller works and how to pass data between child and parent viewcontrollers. It would be great if someone can help on this. If any sample code is available to achive this please let me know.
Any help is much appreciated.
You can pass around the same collection view controller instance. Add it in viewWillAppear and remove in viewDidDisappear in first and second classes. Here is a sample code that you could use,
extension UIColor {
class func randomColor() -> UIColor {
let red = CGFloat(arc4random_uniform(255)) / 255.0
let green = CGFloat(arc4random_uniform(255)) / 255.0
let blue = CGFloat(arc4random_uniform(255)) / 255.0
return UIColor(red: red, green: green, blue: blue, alpha: 1.0)
}
}
class MyCollectionViewController: UICollectionViewController {
let data: [UIColor]
init(data: [UIColor]) {
self.data = data
let layout = UICollectionViewFlowLayout()
layout.itemSize = CGSizeMake(100, 100)
layout.scrollDirection = UICollectionViewScrollDirection.Vertical
super.init(collectionViewLayout: layout)
}
override func viewDidLoad() {
super.viewDidLoad()
collectionView?.registerClass(UICollectionViewCell.self, forCellWithReuseIdentifier: "cell")
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return data.count
}
override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier("cell", forIndexPath: indexPath)
cell.backgroundColor = data[indexPath.item]
return cell
}
}
class FirstViewController: UIViewController {
lazy var myData:[UIColor] = {
var allData = [UIColor]()
for i in 0 ..< 20 {
allData.append(UIColor.randomColor())
}
return allData
}()
var collectionViewController: MyCollectionViewController!
override func viewDidLoad() {
super.viewDidLoad()
collectionViewController = MyCollectionViewController(data: self.myData)
let barButton = UIBarButtonItem(title: "Show next", style: .Plain, target: self, action: "showNext:")
navigationItem.rightBarButtonItem = barButton
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
let collectionView = collectionViewController.view
collectionView.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(collectionView)
addChildViewController(collectionViewController)
collectionView.topAnchor.constraintEqualToAnchor(view.topAnchor).active = true
collectionView.bottomAnchor.constraintEqualToAnchor(view.bottomAnchor).active = true
collectionView.leftAnchor.constraintEqualToAnchor(view.leftAnchor).active = true
collectionView.rightAnchor.constraintEqualToAnchor(view.rightAnchor).active = true
collectionViewController.didMoveToParentViewController(self)
}
override func viewWillDisappear(animated: Bool) {
super.viewDidDisappear(animated)
collectionViewController.willMoveToParentViewController(nil)
collectionViewController.view.removeFromSuperview()
collectionViewController.removeFromParentViewController()
}
func showNext(sender: AnyObject) {
let secondViewController = SecondViewController(collectionViewController: collectionViewController)
navigationController?.pushViewController(secondViewController, animated: true)
}
}
class SecondViewController: UIViewController {
var collectionViewController: MyCollectionViewController!
init(collectionViewController: MyCollectionViewController) {
self.collectionViewController = collectionViewController
super.init(nibName: nil, bundle: nil)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
let collectionView = collectionViewController.view
view.addSubview(collectionView)
collectionView.translatesAutoresizingMaskIntoConstraints = false
addChildViewController(collectionViewController)
collectionView.topAnchor.constraintEqualToAnchor(view.topAnchor).active = true
collectionView.bottomAnchor.constraintEqualToAnchor(view.bottomAnchor).active = true
collectionView.leftAnchor.constraintEqualToAnchor(view.leftAnchor).active = true
collectionView.rightAnchor.constraintEqualToAnchor(view.rightAnchor).active = true
collectionViewController.didMoveToParentViewController(self)
}
override func viewWillDisappear(animated: Bool) {
super.viewDidDisappear(animated)
collectionViewController.willMoveToParentViewController(nil)
collectionViewController.view.removeFromSuperview()
collectionViewController.removeFromParentViewController()
}
}
I have a Set of Answers you can use,
My source Code is ParentViewController and ChildViewController are
same viewController to be declared.
First you create the ParentViewController and add the
UICollectionView then set the Cell size in ParentViewController.
Second you create UICollectionViewCell in same parentViewController,
then add what u need Label or Buttons to be declare.
In ParentViewController class declare 'UICollectionViewDelegate',
Ex: class MyViewController: UIViewController, UICollectionViewDelegate
Then Create UICollectionViewDelegate methods and i have put my
methods below,
func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
return 1
}
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return arrayvalue.count
}
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier("reuseIdentifier", forIndexPath: indexPath)
// Configure the cell
let baseView = cell.viewWithTag(101)
let titleLabel = baseView?.viewWithTag(102) as! UILabel
titleLabel.text = arrayvalue[indexPath.row] as String
return cell
}
func collectionView(collectionView: UICollectionView,
layout collectionViewLayout: UICollectionViewLayout,
sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
return CGSizeMake(CellSize)
}
func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath)
{
collectionView.deselectItemAtIndexPath(indexPath, animated:true)
let storyBoard = UIStoryboard(name: "storyboardName", bundle: nil)
let name: classname = storyBoard.instantiateViewControllerWithIdentifier("reuseIdentifier") as! AnotherViewController
self.navigationController?.pushViewController(name, animated: true)
}
Very Important to give storyboard 'reuseIdentifier' value and also
give inside the class cellForItemAtIndexPath reuseIdentifier, example this line
let cell = collectionView.dequeueReusableCellWithReuseIdentifier("reuseIdentifier", forIndexPath: indexPath)
This code was working for me...

tableView:didSelectRowAtIndexPath not called in custom view

I made a popupView to select some object in my project.
Everything works fine except the tableViewDelegate is not called.(DataSource works fine)
I logged value of tableView.delegate from cellForRowAtIndexPath.It also have the correct value.
Below is my code.
protocol AddressSelectPopupDelegate: NSObjectProtocol {
func addressSelectPopup(selectedContact: Contact) }
class AddressSelectPopupView: UIView, UITableViewDelegate, UITableViewDataSource {
#IBOutlet weak var tableView: UITableView!
weak var parentView: UIView!
weak var delegate: AddressSelectPopupDelegate!
var contactList : [Contact] = []
var selectedContact : Contact?
class func addressSelectPopupView(parentView: UIView, delegate: AddressSelectPopupDelegate) -> AddressSelectPopupView
{
var popupView = UINib(nibName: "AddressSelectPopupView", bundle: NSBundle.mainBundle()).instantiateWithOwner(nil, options: nil)[0] as! AddressSelectPopupView
popupView.parentView = parentView
popupView.delegate = delegate
popupView.tableView.registerNib(UINib(nibName: "AddressInfoTableViewCell", bundle: NSBundle.mainBundle()), forCellReuseIdentifier:"AddressInfoTableViewCell")
popupView.tableView.delegate = popupView
popupView.tableView.dataSource = popupView
return popupView
}
//MARK: - Public Interface
func popup()
{
self.parentView.addSubview(self)
self.loadContactList()
}
func dismiss()
{
self.removeFromSuperview()
}
//MARK: - Private Interface
private func loadContactList()
{
ConnectionManager.connection.loadContactList({ [weak self](contactList) -> Void in
self!.contactList = contactList
dispatch_async(dispatch_get_main_queue(), { () -> Void in
if self!.tableView != nil
{
self!.tableView.reloadData()
}
})
}, failure: { [weak self] () -> Void in
self!.tableView.reloadData()
})
}
//MARK: - UITableView Delegate & DataSource
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return contactList.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell:AddressInfoTableViewCell = tableView.dequeueReusableCellWithIdentifier("AddressInfoTableViewCell") as! AddressInfoTableViewCell
let contact = contactList[indexPath.row]
cell.contact = contact
return cell
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
selectedContact = contactList[indexPath.row]
}
func tableView(tableView: UITableView, willSelectRowAtIndexPath indexPath: NSIndexPath) -> NSIndexPath? {
selectedContact = contactList[indexPath.row]
return indexPath
}
#IBAction func cancelAction(sender: AnyObject) {
self.dismiss()
}
#IBAction func confirmAction(sender: AnyObject) {
//TODO : add confirmAction
if selectedContact != nil
{
self.dismiss()
if delegate.respondsToSelector(Selector("addressSelectPopup:"))
{
delegate.addressSelectPopup(selectedContact!)
}
}
}}
///Update 1
I create a new ViewController (called PopupVC) using the Delegate & DataSource code above.
Way1 : I present the PopupVC from the rootView.
Result : it works fine.
Way2 : I add the View of PopupVC as a subView to rootView, and also add PopupVC as a childViewController to rootView.
Result : Swiping the cell will call didSelectRowAtIndexPath. Tapping only makes the cell be highlighted.
///Update 2
I just noticed that the rootView is presented by another View.
First delete tap gesture of your subview before calling the popoverview. Then only call your UITableViewDelegate inside the popoverview.
To remove gesture from you view, use this code:
self.view.gestureRecognizers?.forEach(self.view.removeGestureRecognizer(_:))
self.view.addSubview(self.customView.view)
Add this to your class :
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
tableView.delegate = self
tableView.dataSource = self
}
Well you shouldn't have delegate and datasource connected both in interface builder and programmatically.
I believe one is badly set and is interfering with the other.
What you can do is try removing the link in interface builder, check what happens and if it is not working add them again but remove the link in the code.

Call back method not calling from UIView to ViewController in Swift

I have two classes CustomSwipOut which is a subclass of UIView and ViewController subclass of UIViewController. The callback method of delegate is not firing in ViewController class from didSelectRowAtIndexPath delegate method of table view defined in CustomSwipeOut. I have done optional binding in ViewController class as var a = CustomSwipeOut(); a.delegate = ViewController()
protocol SendIndexDelegate{
func sendIndex(Int);
}
class CustomSwipeOut: UIView , UITableViewDataSource , UITableViewDelegate {
var label: UILabel = UILabel()
var myNames = ["item1","item2","item3"]
var delegate : SendIndexDelegate?
override init()
{
super.init()
}
override init(frame: CGRect) {
super.init(frame: frame)
self.addCustomView()
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func addCustomView()
{
//add blank subview to the view
var blankView : UIView = UIView(frame: CGRectMake(0, 0, 300, 100))
blankView.backgroundColor = UIColor.greenColor()
self.addSubview(blankView)
//creating a tableview programmatically
var tblView : UITableView = UITableView()
tblView.frame = CGRectMake(0, 100, 300, 200)
self.addSubview(tblView)
tblView.delegate = self
tblView.dataSource = self
tblView.registerClass(UITableViewCell.self, forCellReuseIdentifier: "myCell")
}
//pragma mark- table view data source methods
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell : UITableViewCell = tableView.dequeueReusableCellWithIdentifier("myCell") as UITableViewCell
cell.textLabel?.text = self.myNames[indexPath.row]
return cell
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.myNames.count
}
//pragma mark - table view delegate methods
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
var row = indexPath.row
if let temp = self.delegate {
delegate?.sendIndex(row)
}else{
println("optional value contains nill value")
}
}
//ViewController Class
class ViewController: UIViewController , SendIndexDelegate {
var myView :UIView = UIView()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
var a = CustomSwipeOut()
a.delegate = ViewController()
let rect: CGRect = CGRect (x: self.view.frame.size.width, y :50 , width: self.view.frame.size.width-100, height: self.view.frame.size.height-100)
self.myView = CustomSwipeOut(frame : rect )
self.view.addSubview(self.myView)
//optional chaining
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
#IBAction func showSideMenu() {
UIView.animateWithDuration(0.2, animations:{
self.myView.frame = CGRectMake(100, 50,self.view.frame.size.width-100,self.view.frame.size.height-100)
} )
}
//delegate method
func sendIndex(row : Int)
{
switch row {
case 0:
println("index o clicked")
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let vc = storyboard.instantiateViewControllerWithIdentifier("MoneySum") as UIViewController
self.presentViewController(vc, animated: true, completion: nil)
println("index 2 clicked")
...
default:
println("no index")
}
}
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
let rect: CGRect = CGRect (x: self.view.frame.size.width, y :50 , width: self.view.frame.size.width-100, height: self.view.frame.size.height-100)
var a = CustomSwipeOut(frame : rect)
a.delegate = self
self.myView = a
self.view.addSubview(self.myView)
//optional chaining
}

Resources