2015-06-20 73 views
0

在我的swift項目中,我有一個按鈕,我想在標籤上打印這個按鈕被按下的時間。按下按鈕時發生的操作 - swift

我該如何解決這個問題?

+0

你有什麼企圖這麼遠嗎? – Blip

+0

沒有任何工作... –

+1

Try yourLabel.text = NSDate.description() –

回答

0

下面是如何以編程方式創建按鈕,並在按下按鈕時在標籤中打印文本。

override func viewDidLoad() { 
     super.viewDidLoad() 
     // Do any additional setup after loading the view, typically from a nib. 
     let myFirstButton = UIButton() 
     myFirstButton.setTitle("Tap Me", forState: .Normal) 
     myFirstButton.setTitleColor(UIColor.blueColor(), forState: .Normal) 
     myFirstButton.frame = CGRectMake(10, 50, 320, 40) 
     myFirstButton.addTarget(self, action: "pressed:", forControlEvents: .TouchUpInside) 
     self.view.addSubview(myFirstButton) 
    } 

func pressed(sender: UIButton!) 
{ 
    [email protected]"Your Text is here" 
} 
+0

非常感謝! –

0

添加到DHEERAJ的回答,您只需要添加如下代碼func pressed(sender: UIButton!)達到你需要的東西:

let date = NSDate() 
let dateFormatter = NSDateFormatter() 
dateFormatter.dateStyle = .MediumStyle 
let dateString = dateFormatter.stringFromDate(date) 
yourLabelName.text = dateString 

希望這可以幫助。

0

要顯示按鈕被點擊了多少次,您可以使用類變量。

class SampleViewController: UIViewController { 

var counter : Int! 
@IBOutlet weak var yourLabelName: UILabel! 

override func viewDidLoad() { 
    super.viewDidLoad() 

    // Do any additional setup after loading the view, typically from a nib. 
    counter = 1 
    let myFirstButton = UIButton(frame: CGRectMake(10, 50, 320, 40)) 

    myFirstButton.setTitle("Tap Me", forState: .Normal) 
    myFirstButton.setTitleColor(UIColor.blueColor(), forState: .Normal) 
    myFirstButton.addTarget(self, action: "pressed:",forControlEvents: .TouchUpInside) 
    self.view.addSubview(myFirstButton) 
} 

func pressed(sender: UIButton!) 
{ 
    yourLabelName.text = "Pressed : \(counter)" 
    counter = counter + 1 
} 

}