我按照以下教程更改了分段控件的颜色: http://goddess-gate.com/dc2/index.php/post/454
但是,我正在努力理解代码并使用选定的段加载视图。换句话说,我已经设法将我的分段控件的颜色更改为黑色,但它只在我选择一个段而不是在加载视图时才会发生。加载视图时,它只显示为灰色。此外,如果我想重置为原始灰色或更改视图中分段控件的颜色,将如何消除黑色并返回灰色且未选中的所有内容?
有人可以指出我究竟是什么以及为什么,我是否需要添加到viewDidLoad或viewWillAppear方法?
以下是代码:
NSInteger static compareViewsByOrigin(id sp1, id sp2, void *context)
{
// UISegmentedControl segments use UISegment objects (private API). Then we can safely
// cast them to UIView objects.
float v1 = ((UIView *)sp1).frame.origin.x;
float v2 = ((UIView *)sp2).frame.origin.x;
if (v1 < v2)
return NSOrderedAscending;
else if (v1 > v2)
return NSOrderedDescending;
else
return NSOrderedSame;
}
动作方法
-(IBAction)seleccionarSegmented:(id)sender {
int numSegments = [miSegmentedControl.subviews count];
for( int i = 0; i < numSegments; i++ ) {
[[miSegmentedControl.subviews objectAtIndex:i] setTintColor:nil];
[[miSegmentedControl.subviews objectAtIndex:i] setTintColor:[UIColor colorWithRed:200/255.0 green:200/255.0 blue:200/255.0 alpha:1]];
}
NSArray *sortedViews = [miSegmentedControl.subviews sortedArrayUsingFunction:compareViewsByOrigin context:NULL];
[[sortedViews objectAtIndex:miSegmentedControl.selectedSegmentIndex] setTintColor: [UIColor blackColor]];
for (id view in miSegmentedControl.subviews) {
[view removeFromSuperview];
}
for (id view in sortedViews) {
[miSegmentedControl addSubview:view];
}
}
答案 0 :(得分:1)
从swift 3开始,将此代码放在viewDidLoad()
或ViewDidAppear()
//this sets the value of the index that you want to call
let segmentedControlIBOutlet = 0
//this calls the actions for that index
segmentedControlAction(segmentedControlIBOutlet as AnyObject)
答案 1 :(得分:0)
在-viewDidLoad中,尝试拨打[self seleccionarSegmented:miSegmentedControl]
(希望我的名字合适。