Oct 28, 2008

(iPhone) How to customize an UISwitch's text

In the UISwitch Class Reference, it said "The UISwitch class is not customizable". But i saw UISwitch's texts are not "ON/OFF" in some apps, in the UISwitch Class Reference doesn't contain such methods to change the defalut text. I just got the solution from iPhone Dev SDK Forum, someone posted these methods:

- (_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];
}

or

[(UILabel *)[[[[[[yourSwitch subviews] lastObject] subviews] objectAtIndex:2] subviews] objectAtIndex:0] setText:@"LeftText"];

[(UILabel *)[[[[[[yourSwitch subviews] lastObject] subviews] objectAtIndex:2] subviews] objectAtIndex:1] setText:@"RightText"];

_UISwitchSlider? what's that? I think you must have the same question? we can't find this class in the official reference documents. You can check by youself, it really exists in the official SDK, using [yourSwitch subviews] could show you that your UISwitch has an array of _UISwitchSlider, and then you can finally find your UISwitch contains 2 UILabel objects, and we can change their values.

I don't know if the future SDK will documentation these stuff, and i'm afraid there definitely has some other "hidden" methods, i can't understand why Apple doing this for developer, if they would like to release a SDK for public, they should release the whole documents.

1 comment:

williamty said...

Hi, guy?
you are so smart to open such professional blog. This is good for public to communicate and exchange on the views of methodology and thought in IT field.
Keep on going!
Thank!