Search code examples
xcodeswiftdelegation

Xcode delegate link to object


I am new to Xcode IDE and to swift and I'm trying to understand better how it works.

I'm aware that it's possible to make a delegation to an UI element, for example, a comboBox. This allows for working with methods that NSComboBoxDelegate supports. That's all fine. I understand how one comboBox can be linked to the method.

My question is: if there are two comboBox elements with delegation to a single .swift file, how do I define which one will "trigger" the method, for example, comboBoxSelectionDidChange? Do I have to have separate .swift files? Does the method work whenever each is changed? Is there a way to link each object to each method, as it's possible to do with outlets and actions?

I believe it's a simple question and probably one that programmers will answer with ease, but for beginners the abstraction and the simpler gapping holes slow comprehension too much.


Solution

  • Your Elements, for example UIPicker, can use the same delegate methods. You need to therefore differentiate between them by a tag. Or by actual reference. You need to give each one of your 'combo boxes' a tag first obviously, before you can use the tag option.

    For Example:

    func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int)
        {
            if(pickerView.tag == 0)
            {
                //do whatEver you want with the picker that has tag 0
            }
            else if(pickerView.tag == 1)
            {
                //do whatEver you want with the picker that has tag 1
            }
        }
    

    Or by reference:

    func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int)
        {
            if(pickerView == self.cityPicker)
            {
                //do whatEver you want with the city picker
            }
            else if(pickerView = self.countryPicker)
            {
                //do whatEver you want with the country picker
            }
        }