如何将存储电话号码的变量分配给按钮以拨打该号码?
我正在使用Swift。这是我的代码:
func base() {
var myBase = sharedDefaults!.objectForKey("base") as? String
if myBase != nil {
if myBase == "FRA" {
titleLabel.text = "FRANKFURT"
adressLabel.text = "some adress"
var phone = "+49123456 69 69804616"
coorPhone.setTitle("Duty Desk : \(phone)", forState: .Normal)
logoImage.image = UIImage(named: "flaggermany")
} else if myBase == "LHR" {
titleLabel.text = "LONDON"
adressLabel.text = "some adress"
var phone = "+44123456"
coorPhone.setTitle("Duty Desk : \(phone)", forState: .Normal)
logoImage.image = UIImage(named: "flaguk")
}
}
@IBAction func phoneButtonPressed(sender: AnyObject) {
// let telUrlString = "tel://" + phone
// UIApplication.sharedApplication().openURL(NSURL(string: "\ (telUrlString)")!)
}
答案 0 :(得分:2)
您可以通过在类声明的下方声明它,将phone
变量声明为您班级的全局变量,如下所示:
class ViewController: UIViewController {
let sharedDefaults = NSUserDefaults.standardUserDefaults()
var phone = ""
}
通过这种方式声明,您可以在班级的任何位置访问它,现在您可以在函数中以这种方式为其赋值:
func base() {
var myBase = sharedDefaults.objectForKey("base") as? String
if myBase != nil {
if myBase == "FRA" {
titleLabel.text = "FRANKFURT"
adressLabel.text = "some adress"
phone = "+49123456 69 69804616"
coorPhone.setTitle("Duty Desk : \(phone)", forState: .Normal)
logoImage.image = UIImage(named: "flaggermany")
}
else if myBase == "LHR" {
titleLabel.text = "LONDON"
adressLabel.text = "some adress"
phone = "+44123456"
coorPhone.setTitle("Duty Desk : \(phone)", forState: .Normal)
logoImage.image = UIImage(named: "flaguk")
}
}
}
之后你可以用这种方式进入另一个功能:
@IBAction func phoneButtonPressed(sender: AnyObject) {
if let url = NSURL(string: "tel://\(phone)") {
UIApplication.sharedApplication().openURL(url)
}
}
希望这会对你有所帮助。
答案 1 :(得分:1)
@IBAction func phoneButtonPressed(sender: UIButton) {
if let url = NSURL(string: "tel://\(phone)") {
UIApplication.sharedApplication().openURL(url)
}
}
如果在viewController.swift文件的顶部定义变量phone(在类调用之下),则可以使用此代码,这样就可以在函数中访问它。