Как изменить цвет границы UISegmentedControl в iOS7?


Как изменить цвет границы сегментированного контроллера в iOS7 без изменения цвета текста?


Было бы идеально, если бы я мог оставить линию между сегментами как есть (то есть того же цвета, что и текст), но если изменение цвета границы подразумевает изменение этой линии, это тоже было бы нормально.

Также обратите внимание, что текст (и линии между сегментами) имеют цвет, заданный параметром
[segmCtrl setTintColor:choosenTintColor].


person OscarWyck    schedule 04.10.2013    source источник
comment
возможный дубликат iphone ios7 сегментированный UISegmentedControl меняет только цвет границы   -  person iwasrobbed    schedule 04.10.2013
comment
@iWasRobbed Тема, на которую вы ссылаетесь, принимает ответ, который не дает правильного ответа на вопрос. Это просто решает проблему человека, который задал вопрос. Я ищу способ изменить цвет границы, а не цвет текста.   -  person OscarWyck    schedule 06.10.2013


Ответы (3)


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

// Sets the tint color which typically sets the color of the segment images, text, dividers,
// borders, and selected segment. A translucent version of this color is also used to tint a
// segment when it is pressed and transitioning to being selected, as shown on the first
// segment below.
[[UISegmentedControl appearance] setTintColor:[UIColor blackColor]];

// The attributes dictionary can specify the font, text color, text shadow color, and text
// shadow offset for the title in the text attributes dictionary
[[UISegmentedControl appearance] setTitleTextAttributes:@{NSForegroundColorAttributeName:[UIColor redColor]} forState:UIControlStateNormal];

Для одного элемента управления в приложении:

// Sets the tint color which typically sets the color of the segment images, text, dividers,
// borders, and selected segment. A translucent version of this color is also used to tint a
// segment when it is pressed and transitioning to being selected, as shown on the first
// segment below.
self.segControl.tintColor = [UIColor blackColor];

// The attributes dictionary can specify the font, text color, text shadow color, and text
// shadow offset for the title in the text attributes dictionary
[self.segControl setTitleTextAttributes:@{NSForegroundColorAttributeName:[UIColor redColor]} forState:UIControlStateNormal];

Подробнее здесь: https://developer.apple.com/library/content/documentation/UserExperience/Conceptual/UIKitUICatalog/UISegmentedControl.html

person iwasrobbed    schedule 06.10.2013
comment
Спасибо, что нашли время помочь мне. Однако я сам нашел решение, которое, на мой взгляд, лучше (более простое для понимания). - person OscarWyck; 07.10.2013
comment
Используйте UIControlStateSelected вместо UIControlStateNormal, если вы хотите изменить только цвет текста выбранной вкладки. - person devios1; 02.05.2015

Поэтому я решил проблему сам. Мое решение дает границе сегментированного элемента управления другой цвет, и ничего больше.

Чтобы изменить только цвет границы сегментированного элемента управления, я поместил другой сегментированный элемент управления поверх моего старого. Я отключил взаимодействие с пользователем для этого нового и установил изображение для выбранного сегмента на nil.

UIView *header = [[UIView alloc] initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, 40)];
// Header view for my main view

UISegmentedControl *subCat = [[UISegmentedControl alloc] initWithItems:[NSArray arrayWithObjects:@"Segm 1", @"Segm 2", @"Segm 3", @"Segm 4", nil]]; 
// The UISegmentedController which I want to change color for

[subCat setFrame:CGRectMake(5, 5, [UIScreen mainScreen].bounds.size.width - 10, 30)];
[subCat setSelectedSegmentIndex:0];

UISegmentedControl *bcg = [[UISegmentedControl alloc] initWithItems:[NSArray arrayWithObjects:@" ", @" ", @" ", @" ", nil]]; 
// The UISegmentedController I put on top of the other one

UIColor *subColor = [UIColor redColor];
[subCat setTintColor:subColor];
[bcg setFrame:CGRectMake(5, 5, [UIScreen mainScreen].bounds.size.width - 10, 30)];
[bcg setTintColor:[UIColor greenColor]];
[bcg setUserInteractionEnabled:NO];
[bcg setSelectedSegmentIndex:0];
[bcg setImage:nil forSegmentAtIndex:0]; // Removing highlight color


[header addSubview:subCat];
[header addSubview:bcg];

[[self view] addSubview:header];
person OscarWyck    schedule 07.10.2013
comment
Почему бы тебе просто не сделать это? [[Внешний вид UISegmentedControl] setTitleTextAttributes:@{ NSForegroundColorAttributeName: [UIColor redColor] } forState:UIControlStateNormal]; - person Benjamin Stark; 14.01.2014
comment
Отличный обходной путь. Вместо того, чтобы устанавливать для изображения значение nil, предложите установить для индекса фона значение -1. [bcg setSelectedSegmentIndex:-1]; - person Frank Yin; 08.07.2014

Я решаю добавить viewWillAppear mySegmentControl.selectedIndex для всех элементов. Таким образом, цвет оттенка появляется для всех сегментов. Конечно, после выбора всех элементов снова выберите элемент по умолчанию.

person Claudio Castro    schedule 24.10.2013