UISegmentedControl以编程方式分割帧

时间:2014-02-13 13:10:49

标签: ios objective-c uisegmentedcontrol

我正在以下列方式使用分段控件。

    CGFloat segmentWidth = 70;
    CGFloat segmentHeight = 40;
    NSMutableArray *arr = [[NSMutableArray alloc] init];
    for (HCIPGRentDetail *object in self.pgHouse.rents) {
        [arr addObject:object.roomTypeId];
    }
    UISegmentedControl *sharingSegmentControl = [[UISegmentedControl alloc] initWithItems:arr];
    [sharingSegmentControl setApportionsSegmentWidthsByContent:YES];
    sharingSegmentControl.frame = CGRectMake(0, 0, self.pgHouse.rents.count * segmentWidth, segmentHeight);
    for (int i = 0; i < sharingSegmentControl.numberOfSegments; i++) {
        [sharingSegmentControl setWidth:segmentWidth forSegmentAtIndex:i];
        [sharingSegmentControl setTitle:arr[i] forSegmentAtIndex:i];
    }
    sharingSegmentControl.center = CGPointMake(self.view.center.x, currentHeight + sharingSegmentControl.frame.size.height/2);
    currentHeight += sharingSegmentControl.frame.size.height;
    [sharingSegmentControl.layer setBorderColor:[UIColor redColor].CGColor];
    [sharingSegmentControl.layer setBorderWidth:1.0f];
    [sharingSegmentControl setSelectedSegmentIndex:0];
    [sharingSegmentControl setBackgroundColor:[UIColor blueColor]];
    [sharingSegmentControl setSegmentedControlStyle:UISegmentedControlStyleBar];
    [self.mainScrollView addSubview:sharingSegmentControl];

它只显示蓝色背景和红色的段控件,这些段得到一个框架(调试器),如{{0,0},{0,29}}。不明白我错过了什么。

调试器说这个

<__NSArrayM 0x1411be30>(
<UISegment: 0x1411bd60; frame = (0 0; 0 29); opaque = NO; layer = <CALayer: 0x1411bd30>>,
<UISegment: 0x1411a1c0; frame = (0 0; 0 29); opaque = NO; layer = <CALayer: 0x1411b220>>
)

2 个答案:

答案 0 :(得分:0)

我复制了你的代码并对其进行了一些编辑,所以这对我有用:

CGFloat segmentWidth = 70;
CGFloat segmentHeight = 40;

UISegmentedControl *sharingSegmentControl = [[UISegmentedControl alloc] initWithItems:@[@"AAA", @"BBB"]];
//[sharingSegmentControl setApportionsSegmentWidthsByContent:YES];
sharingSegmentControl.frame = CGRectMake(0, 0, sharingSegmentControl.numberOfSegments * segmentWidth, segmentHeight);
for (int i = 0; i < sharingSegmentControl.numberOfSegments; i++) {
    [sharingSegmentControl setWidth:segmentWidth forSegmentAtIndex:i];
    //[sharingSegmentControl setTitle:arr[i] forSegmentAtIndex:i];
}
[sharingSegmentControl.layer setBorderColor:[UIColor redColor].CGColor];
[sharingSegmentControl.layer setBorderWidth:1.0f];
[sharingSegmentControl setSelectedSegmentIndex:0];
[sharingSegmentControl setBackgroundColor:[UIColor blueColor]];
[sharingSegmentControl setSegmentedControlStyle:UISegmentedControlStyleBar];
[self.view addSubview:sharingSegmentControl];

答案 1 :(得分:0)

原来,色调是问题所在。也许段控制将色调默认为明暗色左右。

不知何故,当我设置色彩时。我的框架正确,显示正确。