Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom delegate method in Swift

Tags:

ios

swift

I am working on an app where I need to have a delegate method for button to identify that which button is pressed by user.Below is the code , please let me know where I am making mistake.Delegate is not working,there is no error,no crash.

import UIKit
@objc protocol SAlertViewDelegate {

optional func clickedButtonTitle(title:String)
}

class CustomAlertView: UIView {

var delegate:SAlertViewDelegate?
 func button1Action(sender: UIButton?) {

    let titleLabel=sender?.titleLabel?.text
    self.delegate?.clickedButtonTitle!(titleLabel!)
    removeFromMainView()
}

}

View Controller :-

import UIKit

class CurrentImageVC: UIViewController,SAlertViewDelegate
{
var alert:CustomAlertView=CustomAlertView()
override func viewDidLoad() {
    super.viewDidLoad()

    alert.delegate=self

    }

//MARK: Custom Delegate
func clickedButtonTitle(title:String)
{
    println(title)
}

}
like image 421
Saurabh Mishra Avatar asked Apr 25 '26 09:04

Saurabh Mishra


1 Answers

The problem is that you need to assign delegate to object which you are using to add the subview.

let alertSubView: CustomAlertView = CustomAlertView()
alertSubView.frame=CGRectMake(0,0,1024,768)
alertSubView.delegate=self
self.view.addSubview(alertSubView)
like image 132
Sohil R. Memon Avatar answered Apr 27 '26 23:04

Sohil R. Memon