Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

iOS

Call to phone number when touching label

Hi. How I can make a label with phone number callable when touching this label using Swift language

1 Answer

Hey Arman! Here is what an action function from a button in swift that will call a number, the inside section UIApplication will work if attached to a label, but for simplicity this is an action function from a button.

@IBAction func callButton(sender: AnyObject) {
      UIApplication.sharedApplication().openURL(NSURL(string: "tel://1234567890"))
}

Hope this helps you!

Hi, Ryan. Thanks for answers. Is it callable from iOS Simulator? Because I can't make call from simulator

Unfortunatley you cannot test this on the simulator because the simulator doesn't have any phone functionality, but testing it on a device, as I did, will work!

How to attach this to label? I mean when touching label with phone number to call to this number

Well UILabel's do not have any default touch interaction behavior, but you can monitor the touches on the screen and check if that touch is in the frame of the label!

let phoneNumberLabel:UILabel = UILabel(frame: CGRectMake(85, 220, 120, 45))

    override func viewDidLoad() {
        super.viewDidLoad()
        phoneNumberLabel.bounds = CGRectMake(CGRectGetMidX(self.view.frame), 220, 120, 45)
        phoneNumberLabel.text = "Call Number"
        self.view.addSubview(phoneNumberLabel)
    }

    override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {
        for touch: AnyObject in touches {
            let location = touch.locationInView(self.view)
            if CGRectContainsPoint(phoneNumberLabel.frame, location) {
                UIApplication.sharedApplication().openURL(NSURL(string: "tel://1234567890"))
            }
        }
    }

This is a complete application that can be pasted into a single view application template and experimented with, I hope this helps you!

Thank you very much!!!

No problem! :)