如何设置分段控件的样式?

时间:2012-12-06 13:16:18

标签: objective-c rubymotion

我正在使用Rubymotion创建一个iOS应用。 在其中一个视图中,我使用的是UIsegmentedcontroller,它工作正常。

如何自定义它。我需要为整个背景使用自定义背景图像(这不起作用)和每个按钮的图像(这都有效)。

这是我目前的代码:

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)

我尝试使用此代码:

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

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

但如果我这样做,我会收到此错误:

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

我试过没有外表,但后来我得到了:

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

更新

我尝试了这个,背景上没有显示图片:

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

1 个答案:

答案 0 :(得分:2)

使用 setBackgroundImage:forState:barMetrics:

它设置给定状态和条形度量的背景图像。

您可以在Apple.Developer documentation

中查看详细信息

示例代码:

取自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];