簡體   English   中英

查找視圖上的所有detailDislosureButtons

[英]Finding all detailDislosureButtons on a view

我試圖在UIViewController上找到特定類型( detailDisclosure )的所有按鈕。 要在視圖上找到所有UIButtons ,我將使用以下代碼:

let buttons = view.subviews.filter{$0 is UIButton}

如何按按鈕類型(在這種情況下為detailDisclosure

我嘗試使用原始值為2的UIButtonType.detailDisclosureUIButtonType.detailDisclosure ,但是出現編譯器錯誤。

    let buttons = view.subviews.filter{$0 is UIButtonType.detailDisclosure}

感謝您的閱讀。

在過濾器關閉中,您首先需要使用條件類型強制轉換運算符( as? )檢查每個視圖是否為UIButton 如果是按鈕,則可以檢查buttonType屬性是否為.detailDisclosure

let buttons = view.subviews.filter {
    guard let button = $0 as? UIButton else {
        return false
    }
    return button.buttonType == .detailDisclosure
}

對於等效的單行解決方案,可以將可選鏈接與buttonType屬性一起使用,但是請注意,必須將類型放在.detailDisclosureUIButtonType )之前,因為無法再推斷出它。

buttons = view.subviews.filter { ($0 as? UIButton)?.buttonType == UIButtonType.detailDisclosure }

嘗試這個 ....

let buttons = view.subviews.filter { (v) -> Bool in
    if let btn = v as? UIButton {
        if btn.buttonType == .detailDisclosure {
            return true
        }
    }
    return false
}

這是2.3版,但您可以在filter方法中執行以下操作

if buton.buttonType == UIButtonType.DetailDisclosure {

}    

這個完美地為我工作:(快速3)

let buttons = view.subviews.filter{$0 is UIButton}

for btn in buttons as! [UIButton] {
    if btn.buttonType == .detailDisclosure {
        print(bin)
    }
}

暫無
暫無

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

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