Используя UISegmentedControl как кнопка

В моем коде я использую a UISegmentedControl как "кнопка" ТОЛЬКО С ОДНИМ сегментом и momentary набор свойств к YES. В версиях SDK до iOS 4 это не было проблемой, но кажется, что теперь iOS 4 требует, чтобы было по крайней мере 2 сегмента. Следующий код выдает исключение:

NSArray *titles = [NSArray arrayWithObject:@"Button Title"];
myButton = [[UISegmentedControl alloc] initWithItems:titles];

и теперь в Интерфейсном Разработчике Вы не можете даже создать UISegmentedControl меньше чем с 2 сегментами. Это регистрирует следующую ошибку при создании:

"Количество свойства сегментов сегментированного управления должно быть больше, чем или равным 2".

Я отчасти озадачен. Какая-либо работа arounds для этого? Я пытался создать a UISegmentedControl с двумя кнопками и затем удаляют ту программно, и это "работает", поскольку она не заставляет приложение отказывать. Я получаю кнопку в iOS 3 и ничто в iOS 4. Какие-либо идеи?

7
задан Adolfo 8 August 2010 в 04:10
поделиться

5 ответов

Действительно странно. У меня все еще отлично работает как в симуляторе iOS4, так и на устройстве (это настоящий рабочий фрагмент из моего кода):

NSArray *laterContent = [NSArray arrayWithObjects: @"Maybe later", nil];
UISegmentedControl *later = [[UISegmentedControl alloc] initWithItems:laterContent];
CGRect frame = CGRectMake(  20,
                          98,
                          self.alert.bounds.size.width/2 - 30,
                          30);

later.frame = frame;

later.selectedSegmentIndex = -1;

[later addTarget:self action:@selector(laterAction:) forControlEvents:UIControlEventValueChanged];

later.segmentedControlStyle = UISegmentedControlStyleBar;
later.tintColor = [UIColor colorWithRed:130.0f/255.0f green:74.0f/255.0f blue:54.0f/255.0f alpha:0.8f];
later.momentary = YES;
later.alpha = 0.9;
6
ответ дан 6 December 2019 в 10:47
поделиться

Пробовали ли вы это:

[myButton removeAllSegments];
[myButton insertSegmentWithTitle:@"Press this" atIndex:0 animated:NO];
7
ответ дан 6 December 2019 в 10:47
поделиться

Well two possibilities:

1) Create a button and the set background image as the single dot of the UISegmentedControl

If your SegmentedControl is a class variable just replace the @property

@property (nonatomic, retain) IBOutlet UIButton *button;

In the viewDidLoad-function add the following

-(void) viewDidLoad
{
    [super viewDidLoad];
    ...
    self.button = [UIButton alloc] init];
    [self.button setBackgroundImage:[UIImage imageNamed:@"segmentedDot.png"] forState:(UIControlState)UIControlStateNormal];
}

2) Set the amount of segments to three of your UISegmentedControl and afterwards set the width to 20 - now only the dot in the middle will be shown. Dont forget, if the user interacts with the UISegmentedControl, set the currentElement again to the second segment, else the dot will be in light grey instead of white state.

3) Place a button or a small view over the unwanted second dot of the UISegmentedControl in InterfaceBuilder. Make sure the backgroundcolor is even. When you are using a button set the state for "user interaction" in attribute inspector to disabled. As type I would chose "custom" since you won't have some borders in your button ;) Now male again sure, that always the first dot is the active Element.

However I think solution one should be the way you should go, since Apple thought something about it, when they disabled the 1-dot-SegmentedControl. Since you are using the Control as a button the Element you are looking fpr should be a button. ;)

0
ответ дан 6 December 2019 в 10:47
поделиться

В iOS 4 нет обходного пути. Если вам нужна эта функция, сообщите об ошибке (улучшение запрос) на bugreport.apple.com .

0
ответ дан 6 December 2019 в 10:47
поделиться

Это не совсем решение, связанное с кодом, но: Я столкнулся с аналогичной проблемой и в итоге нарисовал свои собственные похожие ресурсы в Photoshop. Сделать это было не так уж и сложно, и убрал особенно неприятный "запах кода", IMO.

3
ответ дан 6 December 2019 в 10:47
поделиться
Другие вопросы по тегам:

Похожие вопросы: