函數的代碼來至iphone開發祕籍,Thanks Erica Sadun。
UISwitch類:
UISwitch類的單薄到我不知道該說什麼了。不過,UIControl對象通常是由一系列的子視圖構建的。通過導航控件的視圖,可以公開的定製通常不能從標準SDK中訪問的對象。這種定製依賴於對控件子視圖樹的理解,通過下面這樣的函數可以遞歸遍歷視圖樹,就可以瞭解每一個視圖了。
- (void)explode:(id)aView level:(int)aLevel {
for (int i = 0; i < aLevel; i++)
printf("-");
printf("%s:%s/n",[[[aView class] description] UTF8String],[[[aView superclass] description] UTF8String]);
for(UIView *subview in [aView subviews])
[self explode:subview level:(aLevel + 1)];
}
初始化級別爲0,打出來的結果是:
UISwitch:UIControl
-_UISwitchSlider:UISlider
--UIImageView:UIView
--UIImageView:UIView
--UIView:UIResponder
---UILabel:UIView
---UILabel:UIView
--UIImageView:UIView
然後就可以開始封裝自定義UISwitch字體和字體顏色的定製功能
@interface UISwitch (extended)
- (void) setAlternateColors:(BOOL) boolean;//這是文檔未記錄的特性,顯示爲橘黃色的背景。
@end
@interface _UISwitchSlider : UIView
@end
@interface UICustomSwitch : UISwitch
- (void) setLeftLabelText: (NSString *) labelText;
- (void) setRightLabelText: (NSString *) labelText;
@end
@implementation UICustomSwitch
- (_UISwitchSlider *) slider {
return [[self subviews] lastObject];
}
- (UIView *) textHolder {
return [[[self slider] subviews] objectAtIndex:2];
}
- (UILabel *) leftLabel {
return [[[self textHolder] subviews] objectAtIndex:0];
}
- (UILabel *) rightLabel {
return [[[self textHolder] subviews] objectAtIndex:1];
}
- (void) setLeftLabelText: (NSString *) labelText {
[[self leftLabel] setText:labelText];
}
- (void) setRightLabelText: (NSString *) labelText {
[[self rightLabel] setText:labelText];
}
@end
下面是測試代碼:
- (void)loadView
{
contentView = [[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease];
contentView.backgroundColor = [UIColor whiteColor];
UICustomSwitch *switchView = [[UICustomSwitch alloc] initWithFrame:CGRectZero];
[switchView setCenter:CGPointMake(160.0f,170.0f)];
[contentView addSubview:switchView];
[switchView release];
switchView = [[UICustomSwitch alloc] initWithFrame:CGRectZero];
[switchView setCenter:CGPointMake(160.0f,200.0f)];
[switchView setAlternateColors:YES];
[contentView addSubview:switchView];
[switchView release];
switchView = [[UICustomSwitch alloc] initWithFrame:CGRectZero];
[switchView setCenter:CGPointMake(160.0f,230.0f)];
[switchView setLeftLabelText: @"YES"];
[switchView setRightLabelText: @"NO"];
[contentView addSubview:switchView];
[switchView release];
switchView = [[UICustomSwitch alloc] initWithFrame:CGRectZero];
[switchView setCenter:CGPointMake(160.0f,260.0f)];
[switchView setLeftLabelText: @"ABC"];
[switchView setRightLabelText: @"DEF"];
[[switchView rightLabel] setFont:[UIFont fontWithName:@"Georgia" size:16.0f]];
[[switchView leftLabel] setFont:[UIFont fontWithName:@"Georgia" size:16.0f]];
[[switchView leftLabel] setTextColor:[UIColor yellowColor]];
[contentView addSubview:switchView];
[switchView release];
self.view = contentView;
}
這樣子定製後的結果老強大了(圖1)。
圖 1 圖2
最後,我們選擇了使用資源給出的兩張圖(圖2),結果是我們放棄了那個平滑切換的動畫把它做成了一個按鈕,點一下換一張圖片,記住一個狀態。