2016-11-06 24 views
1

我是Swift的新手,我認爲這是編程iOS的一個基本問題。在Swift3中使用類自定義按鈕及其突出顯示的狀態

我的故事板中有三個按鈕,我想定製按下按鈕一次,兩次和三次的方式。

我也有三個主題(粉色,藍色和橙色)。我想要做的是創建三個新的類叫做粉紅色,藍色和橙色。SWIFT

我不想以編程方式創建它們,只能以編程方式創建它們。

我缺乏瞭解的是我如何調用該函數(例:「ButtonIsPressed」)從我pink.swift類到我@IBAction和@IBOutlet主視圖控制器,這也是對象導向(即我不想爲每個按鈕創建一個功能)?

我無法真正找到一個體面和最新的Swift 3教程,對此主題的任何幫助或建議將不勝感激。

爲何不能像?:

@IBAction func buttonPressed(_ sender: UIButton!) { 
    self.backgroundColor = myPinkCGolor 
} 
+0

我說得對理解你,你要更改按鈕的顏色。德依靠他們的計數?例如,1按 - 紅色,再次按(2按) - 黑色等... –

回答

1

我認爲shallowThought的答案將適用於基於特定命名的IBOutlet的按鈕狀態來更改backgroundColor。

我在故事板中有三個按鈕,我想定製這些按鈕看起來如何按下一次,兩次和三次。

如果你想保持「狀態」,就像在一個「計數器」中點擊或點擊一個按鈕的次數一樣,你可以使用按鈕的「標籤」屬性。將它設置爲零,並在您的IBAction函數中增加它。 (就像shallowThought說的那樣,使用.touchUpInside和.touchDown來處理事件。)

另外,你有一個未成年人 - 但很重要! - 事情錯在你的代碼Brewski:

@IBAction func buttonPressed(_ sender: UIButton!) { 
    self.backgroundColor = myPinkCGolor 
} 

應該是:

@IBAction func buttonPressed(_ sender: UIButton!) { 
    sender.backgroundColor = myPinkCGolor 
} 

所以一切結合 - 最多投票shallowThought(也改變了他對AnyObject和UIButton的使它斯威夫特3.x的語法上在UIColors - 並最終將這個注意,沒有必要對一個IBOutlet,你可以在IB連線了一切沒有子:

// .touchUpInside event 

// can be adapted to show different color if you want, but is coded to always show white color 

@IBAction func buttonClicked(sender: UIButton) { 
    sender.backgroundColor = UIColor.whiteColor() 
} 

// .touchDown event 

// will show a different color based on tap counter 

@IBAction func buttonReleased(sender: UIButton) { 
    switch sender.tag { 
    case 1: 
     sender.backgroundColor = UIColor.blue 
    case 2: 
     sender.backgroundColor = UIColor.red 
    case 3: 
     sender.backgroundColor = UIColor.green 
    default: 
     sender.backgroundColor = UIColor.yellow 
    } 
    sender.tag += 1 
} 
+0

謝謝,幫助了很多,特別是發件人。語法在我之前丟失了。唯一的問題是我無法使用標籤,因爲我已經在使用具有唯一編號的標籤來實現其他功能,但是我會讓它起作用。 – Brewski

0

沒有梅索德設置的backgroundColor一定的狀態,好像有其他UIButton性質一樣簡單,所以你要聽按鈕動作:

class ViewController: UIViewController { 

    @IBOutlet weak var button: UIButton! 

    @IBAction func buttonClicked(sender: AnyObject) { //Touch Up Inside action 
     button.backgroundColor = UIColor.whiteColor() 
    } 

    @IBAction func buttonReleased(sender: AnyObject) { //Touch Down action 
     button.backgroundColor = UIColor.blueColor() 

    } 
    ... 
} 

或設置一個單色圖像image:UIImage, forState:.selected

+0

您的第一句話中是否有拼寫錯誤?不應該是「你**可以**設置backgroundColor」嗎?你的代碼對我來說很好! – dfd

+0

已更新答案,希望更準確。 – shallowThought

+0

謝謝是的,幫助,我會用專櫃 – Brewski