取消选择Segment的默认值

时间:2013-04-25 14:50:31

标签: ios objective-c xcode uisegmentedcontrol

我正在尝试使用数组加载段控件。当我这样做时,选择Male作为默认值。我不希望选择男性或女性,默认情况下都未被选中。

- (id)initWithAnimal:(ITAnimal *)Animal isEdit:(BOOL)isEdit
{
self = [super init];
if (self) {
    // Custom initialization
    _Animal = Animal;
    _genders = [NSArray arrayWithObjects:@"Male", @"Female", nil];
    if (!_Animal) {
        _Animal = [[ITData sharedObject] managedObjectFromName:@"ITAnimal"];
        _Animal.gender = [_genders objectAtIndex:0];

    }
    _isEdit = isEdit;

    // gender controll
    self.genderControl = [[UISegmentedControl alloc] initWithItems:_genders];
    [self.genderControl addTarget:self action:@selector(genderChanged:) forControlEvents:UIControlEventAllEvents];
    }
    return self;
}





}
else if (indexPath.row == 2) {
    BOOL isIn = NO;
    for (id view in cell.contentView.subviews) {
        if ([view isEqual:self.genderControl]) isIn = YES;
    }
    if (!isIn) [cell.contentView addSubview:self.genderControl];

    [cell.detailTextLabel setHidden:_isEdit];
    [self.genderControl setSelectedSegmentIndex:[_genders indexOfObject:content]];

    [self.genderControl setHidden:!_isEdit];
}

4 个答案:

答案 0 :(得分:4)

您应该使用:

[self.genderControl setSelectedSegmentIndex:UISegmentedControlNoSegment];

From Apple's doc:

  

默认值为UISegmentedControlNoSegment(未选择任何段)   直到用户触摸某个细分。将此属性设置为-1以关闭   目前的选择。   UISegmentedControl在忽略此属性时   控件处于瞬时模式。

答案 1 :(得分:2)

您正在寻找

[segmentcontrol setSelectedSegmentIndex:-1];

答案 2 :(得分:1)

我不知道这对某人来说是否仍然存在问题..但如果您使用的是storyBoards ..请选择您放置在viewController上的segmentedIndex,并选择属性Inspector - >分段控制 - >行为取消选中所选的复选框..

答案 3 :(得分:0)

如果您在寻找SwiftUI的解决方案,只需将currentSelection值默认设置为-1。

   struct Parent: View {
    
      @State private var currentSelection = -1
      
      var segmentOptions = ["Green", "Blue"]
      
      var body: some View {
        HStack {
            
            Picker(selection: $currentSelection, label: Text("What is your favorite color?")) {
                ForEach(0..<segmentOptions.count) { index in
                    Text(self.segmentOptions[index]).tag(index)
                }
            }.pickerStyle(SegmentedPickerStyle())
        }
      }
    }