Search code examples
iosswifttoast

How to set action in label?


Here is my code:

added gesture in viewDidLoad

let tap = UITapGestureRecognizer(target: self, action: #selector(tapLabel(tap:)))
            toastLabel.addGestureRecognizer(tap)
            toastLabel.isUserInteractionEnabled = true

func showLongToast( message: String) {        
    toastLabel = UILabel(frame: CGRect(x: controller.view.frame.origin.x + 20, y: controller.view.frame.size.height-200, width: controller.view.frame.size.width - 40, height: 125))
    toastLabel.numberOfLines = 0
    toastLabel.textAlignment = .center
    toastLabel.contentMode = .center
    toastLabel.backgroundColor = UIColor.white.withAlphaComponent(0.7)
    toastLabel.textColor = UIColor(red: 74/255, green: 74/255, blue: 74/255, alpha: 1)
    toastLabel.font = UIFont(name: "Montserrat-Medium", size: 15.0)
    let trimmedString = message.trimmingCharacters(in: .whitespacesAndNewlines)
    let string = NSMutableAttributedString(string: trimmedString)
    string.setColorForText("Enter Manually", with: #colorLiteral(red: 1, green: 0.4196078431, blue: 0.1812392979, alpha: 1))
    toastLabel.attributedText = string
    toastLabel.layer.cornerRadius = 25
    toastLabel.clipsToBounds = true
    controller.view.addSubview(toastLabel)
    controller.view.bringSubviewToFront(toastLabel)
  }

I have call the function from viewController :

showLongToast(message: "Please Hold the lens or choose you can Enter Manually.", controller: self)

But toast message could not set action anymore? Have any idea please post in comment. Thanks.


Solution

  • You are adding the tap gesture recognizer to toastLabel in viewDidLoad(), but then you are creating a new UILabel inside showLongToast()

    Change:

    toastLabel = UILabel(frame: CGRect(x: controller.view.frame.origin.x + 20, y: controller.view.frame.size.height-200, width: controller.view.frame.size.width - 40, height: 125))
    

    in showLongToast() to:

    toastLabel.frame = CGRect(x: controller.view.frame.origin.x + 20, y: controller.view.frame.size.height-200, width: controller.view.frame.size.width - 40, height: 125)