I have an attributed string
set to UILabel
with multiple underlines
, colors
like below image
and I know How to setup a tap gesture for whole label (with enabling user interaction
) and below is my code for what I have done including setting up underline
and setting up font colors
for multiple ranges
.
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var mylabel: UILabel!
var theString = "I have agree with the terms and conditions and privacy policy"
override func viewDidLoad() {
super.viewDidLoad()
mylabel.text = theString
let tap = UITapGestureRecognizer(target: self, action: #selector(ViewController.printme))
mylabel.addGestureRecognizer(tap)
setUnderline(theText: theString)
// Do any additional setup after loading the view, typically from a nib.
}
func printme() {
print("print this")
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func setUnderline(theText : String) {
//set up underline
let textRange1 = NSMakeRange(22, 19)
let textRange2 = NSMakeRange(47, (theText.characters.count-47))
let attributedText = NSMutableAttributedString(string : theText)
attributedText.addAttribute(NSUnderlineStyleAttributeName, value: NSUnderlineStyle.styleSingle.rawValue, range: textRange1)
attributedText.addAttribute(NSUnderlineStyleAttributeName, value: NSUnderlineStyle.styleSingle.rawValue, range: textRange2)
//setup colors
attributedText.addAttribute(NSForegroundColorAttributeName, value: UIColor.red, range: NSRange(location: 22,length: 20))
attributedText.addAttribute(NSForegroundColorAttributeName, value: UIColor.red, range: NSRange(location: 47,length: (theText.characters.count-47)))
mylabel.attributedText = attributedText
}
- The
tap
gesture work forwhole label
. what I want is when user tap on "terms and conditions" fire a different function and and when user tap on "privacy policy" fire another different function. how can I do that.
Note : I want to fire two different functions one for "terms and conditions" tap, and other for "privacy policy" tap, and do not want to just open links