簡體   English   中英

如何使用戶在具有多個UIButton的視圖中僅選擇一個自定義UIButton? 迅捷3

[英]How to make the user select only one custom UIButton in a view with multiple UIButtons? Swift 3

我要在這里做的是,我希望用戶在視圖控制器中選擇一個自定義UIButton,並從中選擇多個UIButton,但是如何使之成為可能,所以當用戶選擇一個UIButton時,如果他想選擇另一個,將取消選擇用戶單擊的第一個UIButton。

這些是未單擊的UIButton

這些是單擊的UIButton

如何使用戶只能選擇一個UIButton? 如果一個UIButton被選中而另一個被選中,則前者將被取消選中

因此,您在按鈕周圍有某種邊框,然后可以遍歷所有按鈕並找到帶有邊框的邊框,將其刪除,然后將邊框設置為新選擇的按鈕。 像這樣:

func buttonSelected(clickedButton: UIButton) {
    for case let button as UIButton in self.view.subviews {
        if button.layer.borderColor == UIColor.black.cgColor {
            // deselect it here by changing the border
            button.layer.borderColor = UIColor.clear.cgColor
        }
        // select the clicked button
        clickedButton.layer.borderColor = UIColor.black.cgColor
    }
}

有時最好知道選擇了哪個,所以我會做這樣的事情。

var selectedButton: UIButton? {
    didSet {
       selectedButton?.layer.borderColor = UIColor.black.cgColor
    }
}

func buttonSelected(sender: UIButton) {
    //Already selected check
    guard selectedButton != sender else { return }
    //Change current selected button properties
    selectedButton?.layer.borderColor = UIColor.clear.cgColor
    //Choose new selected button
    selectedButton = sender
}

如果您想改變很多事情,我建議您繼承UIButton並在其中包含兩個函數。 setSelected()和setUnselected()然后可以這樣工作:

var selectedButton: SelectableButton?

func buttonTapped(sender: SelectableButton) {
     guard selectedButton != sender else { return }
     sender.setSelected()
     selectedButton?.setUnselected()
     selectedButton = sender
}

編輯:我認為這是一個更好的解決方案,然后通過所有子視圖進行for循環。

暫無
暫無

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

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