[英]Check UIButton already exists or not in Swift
我找到了該主題的Objective-C編碼。 但是問題在於,Objective-C中的大多數類和函數在快速編程語言中已被棄用。
我在帶有flagForAction[Boolean Value]
的UITableView內使用UIButton。 所以我想實現的是,如果UIButton創建一次,則無需重新創建它。 因此,為此,我需要檢查UIButton是否已經存在。 有人建議我為此使用標簽的概念,將特定標簽應用於此UIButton並檢查視圖中是否存在。 但是我不知道該怎么做。
設置標簽:
myButton.tag = 1234 // some unique value, probably better to define as an enum or constant
通過標簽檢索視圖(可能在cellForRowAtIndexPath
):
if let myButton = tableviewCell.viewWithTag(1234) { // change tableviewCell for whatever your tableview cell variable name is
// myButton already existed
} else {
// TableviewCell doesn't contain a myButton, so create one here and set the tag as above
}
我以視圖為例。 如果您不想使用按鈕的標簽屬性,則還可以使用按鈕的accessibilityIdentifier屬性來標識按鈕。 例如 :
var button = UIButton(frame: CGRectMake(0, 0, 100, 44))
button.accessibilityIdentifier = "button 1"
self.view.addSubview(button)
在這里,我創建了一個帶有accessibilityIdentifier“ button 1”的按鈕
創建下一個按鈕時,我將在子視圖中檢查它是否包含帶有accessibilityIdentifier“ button 1”的按鈕,如下所示
var subviews : NSArray = self.view.subviews
for button : AnyObject in subviews{
if(button .isKindOfClass(UIButton)){
if(button.accessibilityIdentifier == "button 1"){
println("Button Already Exists")
}else{
println("Create new button")
}
}
}
在迅速2.0
for view in myview.subviews {
if let btn : UIButton = view as? UIButton {
// access button here, either tag or title etc..
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.