Search code examples
objective-crubymotion

How to style a UISegmentedControll?


I am creating an iOS app using Rubymotion. In one of the views I am using a UIsegmentedcontroller and it works fine.

How can I customize it. I need to use custom background image for the whole background (this does not work) and images for each button (this works).

This is my current code:

options = ["Selected","Unselected"]
    segment = UISegmentedControl.alloc.initWithItems(options)
    segment.addTarget(self, action: :'open:', forControlEvents:UIControlEventValueChanged)
    segment.frame = [[0, 0],[320, 40]]
    segment.segmentedControlStyle = 7
    segment.selectedSegmentIndex = 0
    segment.setImage(button, forSegmentAtIndex:0)
    segment.setImage(button2, forSegmentAtIndex:1)

I tried with this code:

segment.apperance.setBackgroundImage(button, forState:UIControlStateNormal , forBarMetrics:UIBarMetricsDefault)

segment.setBackgroundImage(button, forState:UIControlStateSelected , forBarMetrics:UIBarMetricsDefault)

But if I do I get this error:

undefined method `appearance' for #<UISegmentedControl:0x9655a90> (NoMethodError)

I tried without the appearance too but then I got:

undefined method `setBackgroundImage' for #<UISegmentedControl:0x946db70> (NoMethodError)

Update

I tried this and no image is shown on the background:

segment.setBackgroundImage(background, forState:UIControlStateNormal, barMetrics:UIBarMetricsDefault)

Solution

  • Use setBackgroundImage:forState:barMetrics:

    It sets the background image for a given state and bar metrics.

    You can see the details in Apple.Developer documentation

    Sample Code:

    Taken from here

    [[UISegmentedControl appearance] setDividerImage:segmentUnselectedUnselected forLeftSegmentState:UIControlStateNormal rightSegmentState:UIControlStateNormal barMetrics:UIBarMetricsDefault];
    [[UISegmentedControl appearance] setDividerImage:segmentSelectedUnselected forLeftSegmentState:UIControlStateSelected rightSegmentState:UIControlStateNormal barMetrics:UIBarMetricsDefault];
    [[UISegmentedControl appearance] setDividerImage:segUnselectedSelected forLeftSegmentState:UIControlStateNormal rightSegmentState:UIControlStateSelected barMetrics:UIBarMetricsDefault];
    
    [[UISegmentedControl appearance] setBackgroundImage:segmentUnselected forState:UIControlStateNormal barMetrics:UIBarMetricsDefault];
    [[UISegmentedControl appearance] setBackgroundImage:segmentSelected forState:UIControlStateSelected barMetrics:UIBarMetricsDefault];