2015-05-13 19 views
7

Come è possibile associare una proprietà stringa a UIButton in Swift? Non voglio che la stringa appaia come testo del pulsante, semplicemente per essere assegnata al pulsante come identificatore o chiave. Ecco quello che ho finora:Aggiungere una proprietà stringa a un UIButton in Swift

func createAnswerButtons() { 

    var index:Int 
    for index = 0; index < self.currentQuestion?.answers.count; index++ { 

     // Create an answer button view 
     var answer:AnswerButtonView = AnswerButtonView() 
     selection.setTranslatesAutoresizingMaskIntoConstraints(false) 

     // Place into content view 
     self.scrollViewContentView.addSubview(answer) 

     // Add a tapped gesture recognizer to the button 
     let tapGesture:UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: Selector("answerTapped:")) 
     answer.addGestureRecognizer(tapGesture) 

     // Add constraints etc 

     // Set the answer button text 
     let answerText = self.currentQuestion!.answers[index] 
     answer.setAnswerText(answerText) 

     // Set the identifier for each answer button 
     self.identifier = self.currentQuestion!.answerIdentifier[index] 

     // Add to the selection button array 
     self.answerButtonArray.append(answer) 
} 

Quindi penso ho bisogno di qualcosa dopo

// Set the identifier for each answer 
     self.identifier = self.currentQuestion!.answerIdentifier[index] 

Per assegnare l'identificatore al pulsante.

La ragione di ciò è che sto tentando di implementare una logica dell'albero decisionale in modo da poter tenere traccia di ogni pulsante di risposta che viene toccato per generare una stringa di codice che corrisponderà a un risultato finale.

+1

perché non usi la proprietà del tag? –

+0

@LeonardoSavioDabus Tag non è una stringa. È un 'NSInteger'. – nhgrif

+0

@nhgrif So che se non sta visualizzando il testo non vedo la necessità di una stringa –

risposta

8

È possibile sottoclasse UIButton e aggiungere una variabile buttonIdentifier.

class IdentifiedButton: UIButton { 
    var buttonIdentifier: String? 
} 
+2

... e poi mi ricordo sempre di usare questa sottoclasse invece di 'UIButton' ovunque sui tuoi file IB e così via. – nhgrif

+0

Potresti fornire un po 'più di informazioni su questo perché sono completamente bloccato! – brad88

+0

Non ho un UIButton come ho creato le viste Button a livello di programmazione. Ho creato una classe denominata AnswerButtonView e ora nel controller della vista sto creando le viste dei pulsanti – brad88

9

Utilizzando il runtime Objective-C, possiamo aggiungere proprietà alle classi in fase di esecuzione:

extension UIButton { 
    private struct AssociatedKeys { 
     static var DescriptiveName = "nsh_DescriptiveName" 
    } 

    @IBInspectable var descriptiveName: String? { 
     get { 
      return objc_getAssociatedObject(self, &AssociatedKeys.DescriptiveName) as? String 
     } 
     set { 
      if let newValue = newValue { 
       objc_setAssociatedObject(
        self, 
        &AssociatedKeys.DescriptiveName, 
        newValue as NSString?, 
        UInt(OBJC_ASSOCIATION_RETAIN_NONATOMIC) 
       ) 
      } 
     } 
    } 
} 

Aggiunta @IBInspectable permette inoltre di impostare la proprietà descriptiveName attraverso Interface Builder.

Per ulteriori informazioni sul runtime Objective-C, si consiglia di controllare this NSHipster article.

+0

Questa è una grande soluzione, ma il suo OP piuttosto hacky e onestamente non ha bisogno di tutte le istanze 'UIButton' per includere questa proprietà. Rialzato comunque. – Schemetrical

+1

Mi piace essere riabilitato da correzione automatica. – nhgrif

5

È possibile utilizzare accessibilityIdentifier proprietà di UIButton.

@IBOutlet weak var button: UIButton! 
button.accessibilityIdentifier = "Some useful text" 
0

È possibile creare un array con le stringhe che si desidera associare al pulsante. Quindi imposta i tag dei pulsanti sull'indice della stringa che desideri associare al pulsante. Quindi:

var myStrings = ["First","Second","Third"] 

button.tag = //insert a number corresponding to the string index in myStrings that you want for the button 

func buttonPressed(sender: UIButton){ 
    var selectedString = myString[sender.tag] 
} 
2

Usa

button.accessibilityIdentifier = "some text" 

istead di tag.

Problemi correlati