sarunw / SWSegmentedControl

A Android-like tab bar, drop-in replacement for UISegmentedControl.
MIT License
124 stars 24 forks source link

- ? #7

Open amajeedmuazu opened 7 years ago

amajeedmuazu commented 7 years ago

How to set delegate or selection changed method?

D-Link13 commented 7 years ago

Need some help here! Author, please =)

D-Link13 commented 7 years ago

Here is how I had accomplished this task...

  1. Add a protocol to the top of SWSegmentedControl.swift file:
    public protocol SWSegmentedControlDelegate {
    func segmentControl(_segmentControl: SWSegmentedControl, didSelectSegmentAt index: Int)
    }
  2. Add a delegate property to the SWSegmentedControl: public var delegate: SWSegmentedControlDelegate!
  3. Add this line of code to the bottom of didTapButton(_ button: UIButton): self.delegate?.segmentControl(_segmentControl: self, didSelectSegmentAt: self.selectedSegmentIndex)
  4. Add this extension to the object that will delegate selections:
    extension YourObject: SWSegmentedControlDelegate {
    func segmentControl(_segmentControl: SWSegmentedControl, didSelectSegmentAt index: Int) {
        // do things
    }
    }
  5. Finally set the delegate:
    var segmentedControl: SWSegmentedControl {
    let sc = SWSegmentedControl(items: ["item1", "item2"])
    sc.delegate = self
    return sc
    }