簡體   English   中英

Swift - 輕觸UIButton時更改文本的顏色和大小

[英]Swift - Change color and size of text when UIButton is tapped

基本上,我的主屏幕上有三個按鈕。

當我選擇其中一個按鈕時,我希望所選按鈕上的文本更改為粗體並更改顏色(藍色)。

當我選擇一個不同的按鈕時,我希望新選擇的按鈕更改為粗體並更改顏色(藍色),以及之前選擇的按鈕將恢復正常。 (非粗體和黑色文字)

我有這些按鈕向腳本發送動作。

這就是我所擁有的,我似乎無法讓它發揮作用。 非常感謝幫助!

@IBAction func buttonOne(sender: UIButton){
    sender.setTitleColor(UIColor.blueColor(), forState: UIControlState.Highlighted)
}

我試過.Highlighted和。在UIControlState上選擇,似乎都不起作用。 我也試過以下,但我不能讓它工作。

@IBAction func buttonOne(sender: UIButton){
    sender.titleLabel?.textColor = UIColor.blueColor()
}

我認為既然發件人是UIButton,那就是點擊的按鈕,取下它的值並重置它們就行了。 我相信我錯過了一些東西。

謝謝

聽起來像你想要UIControlState.Normal

在大多數情況下,“ Selected不執行任何操作,只有在按下按鈕時才會Highlighted 在此處查看更多信息: https//developer.apple.com/library/ios/documentation/uikit/reference/uicontrol_class/index.html#//apple_ref/doc/constant_group/Control_State

也許你可以做一個變換......

@IBAction func buttonPressed(sender: UIButton) {
    sender.titleLabel!.textColor = UIColor.blueColor()
    sender.transform = CGAffineTransformMakeScale(0.8, 0.8)
}

@IBAction func buttonReleased(sender: UIButton) {
    sender.titleLabel!.textColor = UIColor.redColor()
    sender.transform = CGAffineTransformIdentity
}

為所有按鈕提供標簽,將每個按鈕操作連接到相同的功能並嘗試以下代碼:

@IBAction func butnClicked(sender:UIButton){

    for tg in 1...2 {
        print(sender.tag)
        let tmpButton = self.view.viewWithTag(tg) as? UIButton
        if tmpButton?.tag == sender.tag {
          tmpButton?.setTitleColor(.red, for: .normal)
        } else {
           tmpButton?.setTitleColor(.gray, for: .normal)
        }
    }

希望會有所幫助。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM