Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MonoTouch: UISegmentedControl Select a segment that is already selected

I am attempting to use a UISegmentedControl to control the sort order of my table, in particular I want to register a tap on a segment that is already selected (to inverse my sort). As such, I am trying to raise an UIControlEvent.ValueChanged event whenever any segment is tapped.

I have overridden SelectedSegment from UISegmentedControl and am using this custom class for my element in xcode, however, it appears as though this code is not called when the the Segment control is tapped (It is called when the view is loaded though =S).

[Register("ReselectableSegment")]
public class ReselectableSegment : UISegmentedControl
{
    static Selector selInit       = new Selector("init");  

    [Export("init")]  
    public ReselectableSegment()  
        : base(NSObjectFlag.Empty)  
    {  
        Handle = Messaging.IntPtr_objc_msgSend(this.Handle,  
            selInit.Handle);  
    }  

    public ReselectableSegment (IntPtr handle) : base(handle){}

    public override int SelectedSegment
    {
        [Export ("SelectedSegment:")]
        set { 
            if(this.SelectedSegment == value)
                this.SendActionForControlEvents(UIControlEvent.ValueChanged);

            base.SelectedSegment = value;
        }
    }
}

This question has been asked before at: UISegmentedControl register taps on selected segment, however that question is for ObjC and this question is for C#/Monotouch.

like image 907
Symmetry Avatar asked Dec 03 '25 07:12

Symmetry


1 Answers

The last answer of the question link you provided contains the best (well working) answer (I upvoted it, you should too ;-).

note: from the comments it looks like the previous answers were (maybe) working on iOS4 but not on iOS5.

Here's the code to do what you're looking for. I used the RectangleF .ctor to test it, you might have to add your own .ctor if you're using something else (but it's not as complex as your original code, e.g. no selector should be needed to subclass this).

    class MyUISegmentedControl : UISegmentedControl {

        public MyUISegmentedControl (RectangleF r) : base (r) {}

        public override void TouchesBegan (NSSet touches, UIEvent evt)
        {
            int current = SelectedSegment;
            base.TouchesBegan (touches, evt);
            if (current == SelectedSegment)
                SendActionForControlEvents (UIControlEvent.ValueChanged);
        }
    }
like image 143
poupou Avatar answered Dec 05 '25 20:12

poupou



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!