2015-06-16 7 views
7

मैं button click और button long click पर दो क्रियाओं को ट्रिगर करना चाहता हूं। मैंने अपने इंटरफ़ेस बिल्डर में UIbutton जोड़ दिया है। मैं IBAction का उपयोग करके दो क्रियाओं को कैसे ट्रिगर कर सकता हूं क्या कोई मुझे बता सकता है कि इसे कैसे संग्रहीत किया जाए?एकल प्रेस और लंबी प्रेस घटनाओं के साथ UIButton

इस कोड को मैं एक बटन के लिए इस्तेमाल किया है पर क्लिक किया जाता है

@IBAction func buttonPressed (sender: UIButton) { .... }

मैं इस विधि का उपयोग या मैं लंबे समय से क्लिक के लिए अन्य विधि का उपयोग करने के लिए है कर सकता है?

+1

चेक यह एक http://stackoverflow.com/questions/6660282/uibutton-with-longpress-and-touchup-inside –

उत्तर

17

क्या आप और दबाकर रखें जिसे आप इस तरह से बटन में इशारों में जोड़ सकते हैं टैप से किसी भी कार्रवाई करने के लिए करना चाहते हैं:

@IBOutlet weak var btn: UIButton! 

override func viewDidLoad() { 

    let tapGesture = UITapGestureRecognizer(target: self, action: "Tap") //Tap function will call when user tap on button 
    let longGesture = UILongPressGestureRecognizer(target: self, action: "Long") //Long function will call when user long press on button. 
    tapGesture.numberOfTapsRequired = 1 
    btn.addGestureRecognizer(tapGesture) 
    btn.addGestureRecognizer(longGesture) 
} 

func Tap() { 

    println("Tap happend") 
} 

func Long() { 

    println("Long press") 
} 

इस तरह आप एक बटन के लिए कई विधि जोड़ सकते हैं और आप बस आउटलेट की जरूरत है उस बटन के लिए ..

+0

मैं अपने ui में एकाधिक बटन है, क्योंकि वे सब एक ही है इस मैंने उन्हें इस विधि में मानचित्रित किया है ('@IBAction func बटन दबाया गया (प्रेषक: UIButton') और क्या मैं प्रोग्राम को प्रोग्रामिक रूप से जोड़ सकता हूं? –

+0

फिर आपको सभी बटन के लिए आउटलेट बनाने और इसमें इस इशारे को जोड़ने की आवश्यकता है। और यह विधि काम करेगी सभी बटनों के लिए। –

+0

ओह मेरे पास मेरे यूई में 30 बटन हैं :(आउटलेट का उपयोग किये बिना उन्हें संग्रहित करने का कोई तरीका है? –

0

कस्टम UIButton क्लास क्यों न बनाएं, प्रोटोकॉल बनाएं और बटन को प्रतिनिधि को जानकारी वापस भेज दें। कुछ इस तरह:

//create your button using a factory (it'll be easier of course) 
    //For example you could have a variable in the custom class to have a unique identifier, or just use the tag property) 

    func createButtonWithInfo(buttonInfo: [String: Any]) -> CustomUIButton { 
     let button = UIButton(type: .custom) 
     button.tapDelegate = self 
     /* 
Add gesture recognizers to the button as well as any other info in the buttonInfo 

*/ 
     return button 
    } 

    func buttonDelegateReceivedTapGestureRecognizerFrom(button: CustomUIButton){ 
     //Whatever you want to do 
    } 
संबंधित मुद्दे