您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 程式開發 >> iOS 開發綜合

iOS 開發中 UISwitch 開關控制項的使用方法

編輯:iOS 開發綜合

一、用程式碼動態建立 UISwitch

1. 開啟 Xcode,新建專案 Switch,選擇 Single View Application。

2. 在 ViewController.m 的 viewDidLoad 中加入:

- (void)viewDidLoad {
    [super viewDidLoad];

    UISwitch *switchButton = [[UISwitch alloc] initWithFrame:CGRectMake(50, 100, 20, 10)];
    [switchButton setOn:YES];
    [switchButton addTarget:self action:@selector(switchAction:) forControlEvents:UIControlEventValueChanged];
    [self.view addSubview:switchButton];
}

其中 switchAction: 需要我們自行實作,也就是切換時要收到的回呼。另外別忘了把 switchButton 加到目前的 view 上,呼叫 [self.view addSubview:switchButton]; 否則畫面上什麼都不會出現。

3. 監聽切換事件:

- (void)switchAction:(id)sender {
    UISwitch *switchButton = (UISwitch *)sender;
    BOOL isButtonOn = [switchButton isOn];
    if (isButtonOn) {
        showSwitchValue.text = @"是";
    } else {
        showSwitchValue.text = @"否";
    }
}

showSwitchValue 是另外拖到界面上的 Label,用來顯示目前狀態。

執行效果:

二、用拖拽方式建立 UISwitch

1. 從物件庫拖一個 UISwitch 到 xib 上。

2. 按 alt + command + return 開啟 Assistant Editor,選中 UISwitch 並按住 Control 鍵拖到 ViewController.h。

3. 選擇 Action 方式。

4. 在 .m 中實作 switchAction(與前面動態建立的同名,可先把那段註解掉):

- (IBAction)switchAction:(id)sender {
    UISwitch *switchButton = (UISwitch *)sender;
    BOOL isButtonOn = [switchButton isOn];
    if (isButtonOn) {
        showSwitchValue.text = @"是";
    } else {
        showSwitchValue.text = @"否";
    }
}

三、客製化樣式:HMCustomSwitch

系統預設的 UISwitch 樣式無法客製,實務上若要顯示自訂文字或顏色,常見做法是繼承 UISlider 自己刻一個。下面這個 HMCustomSwitch 就是典型寫法,它的左右兩側各有一個 UILabel,開啟時滑塊滑到最右,關閉時滑到最左:

#import "HMCustomSwitch.h"

@implementation HMCustomSwitch

@synthesize on;
@synthesize tintColor, clippingView, leftLabel, rightLabel;

+ (HMCustomSwitch *)switchWithLeftText:(NSString *)leftText andRight:(NSString *)rightText {
    HMCustomSwitch *switchView = [[HMCustomSwitch alloc] initWithFrame:CGRectZero];
    switchView.leftLabel.text = leftText;
    switchView.rightLabel.text = rightText;
    return [switchView autorelease];
}

- (id)initWithFrame:(CGRect)rect {
    if ((self = [super initWithFrame:CGRectMake(rect.origin.x, rect.origin.y, 95, 27)])) {
        [self awakeFromNib];   // 統一在 awakeFromNib 設定,讓它無論用程式碼或 xib 建立都一致
    }
    return self;
}

- (void)awakeFromNib {
    [super awakeFromNib];

    self.backgroundColor = [UIColor clearColor];

    [self setThumbImage:[UIImage imageNamed:@"switchThumb.png"] forState:UIControlStateNormal];
    [self setMinimumTrackImage:[UIImage imageNamed:@"switchBlueBg.png"] forState:UIControlStateNormal];
    [self setMaximumTrackImage:[UIImage imageNamed:@"switchOffPlain.png"] forState:UIControlStateNormal];

    self.minimumValue = 0;
    self.maximumValue = 1;
    self.continuous = NO;

    self.on = NO;
    self.value = 0.0;

    // 用一個裁剪視圖裝住左右兩個文字標籤
    self.clippingView = [[UIView alloc] initWithFrame:CGRectMake(4, 2, 87, 23)];
    self.clippingView.clipsToBounds = YES;
    self.clippingView.userInteractionEnabled = NO;
    self.clippingView.backgroundColor = [UIColor clearColor];
    [self addSubview:self.clippingView];
    [self.clippingView release];

    NSString *leftLabelText = NSLocalizedString(@"ON", "Custom UISwitch ON label");
    if ([leftLabelText length] == 0) {
        leftLabelText = @"l";   // 用 Helvetica 小寫 L 當 1
    }

    self.leftLabel = [[UILabel alloc] init];
    self.leftLabel.frame = CGRectMake(0, 0, 48, 23);
    self.leftLabel.text = leftLabelText;
    self.leftLabel.textAlignment = NSTextAlignmentCenter;
    self.leftLabel.font = [UIFont boldSystemFontOfSize:17];
    self.leftLabel.textColor = [UIColor whiteColor];
    self.leftLabel.backgroundColor = [UIColor clearColor];
    [self.clippingView addSubview:self.leftLabel];
    [self.leftLabel release];

    NSString *rightLabelText = NSLocalizedString(@"OFF", "Custom UISwitch OFF label");
    if ([rightLabelText length] == 0) {
        rightLabelText = @"O";   // 用 Helvetica 大寫 O 當 0
    }

    self.rightLabel = [[UILabel alloc] init];
    self.rightLabel.frame = CGRectMake(95, 0, 48, 23);
    self.rightLabel.text = rightLabelText;
    self.rightLabel.textAlignment = NSTextAlignmentCenter;
    self.rightLabel.font = [UIFont boldSystemFontOfSize:17];
    self.rightLabel.textColor = [UIColor grayColor];
    self.rightLabel.backgroundColor = [UIColor clearColor];
    [self.clippingView addSubview:self.rightLabel];
    [self.rightLabel release];
}

- (void)layoutSubviews {
    [super layoutSubviews];

    // 把裁剪視圖移到最上層
    [self.clippingView removeFromSuperview];
    [self addSubview:self.clippingView];

    CGFloat thumbWidth = self.currentThumbImage.size.width;
    CGFloat switchWidth = self.bounds.size.width;
    CGFloat labelWidth = switchWidth - thumbWidth;
    CGFloat inset = self.clippingView.frame.origin.x;

    // 依目前 value 計算左標籤位置
    NSInteger xPos = self.value * labelWidth - labelWidth - inset;
    self.leftLabel.frame = CGRectMake(xPos, 0, labelWidth, 23);

    // 右標籤位置
    xPos = switchWidth + (self.value * labelWidth - labelWidth) - inset;
    self.rightLabel.frame = CGRectMake(xPos, 0, labelWidth, 23);
}

- (UIImage *)image:(UIImage *)image tintedWithColor:(UIColor *)tint {
    if (tint != nil) {
        UIGraphicsBeginImageContext(image.size);

        // 先畫遮罩以保留 alpha
        CGContextRef currentContext = UIGraphicsGetCurrentContext();
        CGImageRef maskImage = [image CGImage];
        CGContextClipToMask(currentContext, CGRectMake(0, 0, image.size.width, image.size.height), maskImage);
        CGContextDrawImage(currentContext, CGRectMake(0, 0, image.size.width, image.size.height), image.CGImage);

        [image drawAtPoint:CGPointMake(0, 0)];
        [tint setFill];
        UIRectFillUsingBlendMode(CGRectMake(0, 0, image.size.width, image.size.height), kCGBlendModeColor);

        UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
        return newImage;
    } else {
        return image;
    }
}

- (void)setTintColor:(UIColor *)color {
    if (color != tintColor) {
        [tintColor release];
        tintColor = [color retain];
        [self setMinimumTrackImage:[self image:[UIImage imageNamed:@"switchBlueBg.png"] tintedWithColor:tintColor]
                          forState:UIControlStateNormal];
    }
}

- (void)setOn:(BOOL)turnOn animated:(BOOL)animated {
    on = turnOn;

    if (animated) {
        [UIView beginAnimations:nil context:nil];
        [UIView setAnimationDuration:0.2];
    }

    self.value = on ? 1.0 : 0.0;

    if (animated) {
        [UIView commitAnimations];
    }
}

- (void)setOn:(BOOL)turnOn {
    [self setOn:turnOn animated:NO];
}

- (void)endTrackingWithTouch:(UITouch *)touch withEvent:(UIEvent *)event {
    [super endTrackingWithTouch:touch withEvent:event];
    m_touchedSelf = YES;
    [self setOn:on animated:YES];
}

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    [super touchesBegan:touches withEvent:event];
    m_touchedSelf = NO;
    on = !on;
}

- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
    [super touchesEnded:touches withEvent:event];
    if (!m_touchedSelf) {
        [self setOn:on animated:YES];
        [self sendActionsForControlEvents:UIControlEventValueChanged];
    }
}

- (void)dealloc {
    [tintColor release];
    [clippingView release];
    [rightLabel release];
    [leftLabel release];
    [super dealloc];
}

@end

四、使用這個客製化開關

因為它是繼承自 UISlider,所以可以直接用 center 定位、用 on 控制狀態,也能自訂左右文字、字型與色調:

- (void)loadView {
    UIView *contentView = [[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]];
    self.view = contentView;
    contentView.backgroundColor = [UIColor whiteColor];

    // 標準 ON / OFF
    HMCustomSwitch *switchView = [[HMCustomSwitch alloc] initWithFrame:CGRectZero];
    switchView.center = CGPointMake(160.0f, 20.0f);
    switchView.on = YES;
    [contentView addSubview:switchView];
    [switchView release];

    // 自訂 YES / NO
    switchView = [HMCustomSwitch switchWithLeftText:@"YES" andRight:@"NO"];
    switchView.center = CGPointMake(160.0f, 60.0f);
    switchView.on = YES;
    [contentView addSubview:switchView];

    // 自訂字型與顏色
    switchView = [HMCustomSwitch switchWithLeftText:@"Hello " andRight:@"ABC "];
    switchView.center = CGPointMake(160.0f, 100.0f);
    switchView.on = YES;
    [switchView.leftLabel setFont:[UIFont boldSystemFontOfSize:13.0f]];
    [switchView.rightLabel setFont:[UIFont italicSystemFontOfSize:15.0f]];
    [switchView.rightLabel setTextColor:[UIColor blueColor]];
    [contentView addSubview:switchView];

    // 多行文字
    switchView = [HMCustomSwitch switchWithLeftText:@"Hello\nWorld" andRight:@"Bye\nWorld"];
    switchView.center = CGPointMake(160.0f, 140.0f);
    switchView.on = YES;
    switchView.tintColor = [UIColor orangeColor];
    switchView.leftLabel.font = [UIFont boldSystemFontOfSize:9.0f];
    switchView.rightLabel.font = [UIFont boldSystemFontOfSize:9.0f];
    switchView.leftLabel.numberOfLines = 2;
    switchView.rightLabel.numberOfLines = 2;
    switchView.leftLabel.lineBreakMode = NSLineBreakByWordWrapping;
    switchView.rightLabel.lineBreakMode = NSLineBreakByWordWrapping;
    [contentView addSubview:switchView];

    // 自訂色調
    switchView = [[HMCustomSwitch alloc] init];
    switchView.center = CGPointMake(160.0f, 180.0f);
    switchView.on = YES;
    switchView.tintColor = [UIColor purpleColor];
    [contentView addSubview:switchView];
    [switchView release];

    // 用 l / O 模擬標準樣式
    switchView = [HMCustomSwitch switchWithLeftText:@"l" andRight:@"O"];
    switchView.center = CGPointMake(160.0f, 220.0f);
    [contentView addSubview:switchView];

    // 監聽切換事件
    switchView = [[HMCustomSwitch alloc] init];
    switchView.center = CGPointMake(160.0f, 260.0f);
    switchView.tintColor = [UIColor colorWithRed:125.f/255.f green:157.f/255.f blue:93.f/255.f alpha:1.0];
    [switchView addTarget:self action:@selector(switchFlipped:) forControlEvents:UIControlEventValueChanged];
    [contentView addSubview:switchView];
    [switchView release];

    UIToolbar *toolbar = [[UIToolbar alloc] initWithFrame:CGRectMake(0, 420, 320, 40)];
    toolbar.tintColor = [UIColor colorWithRed:125.f/255.f green:157.f/255.f blue:93.f/255.f alpha:1.0];
    [contentView addSubview:toolbar];

    [contentView release];
}

- (void)switchFlipped:(HMCustomSwitch *)switchView {
    NSLog(@"switchFlipped=%f  on:%@", switchView.value, (switchView.on ? @"Y" : @"N"));
}

最後補充一點實務建議:UISwitch 本身的 frame 寬高由系統決定,你在 initWithFrame 傳入的 20×10 實際上不會生效,要調整位置應該改 center 或直接設定 frame 的 origin。另外若在 iOS 7 之後的新專案裡需要自訂文字,其實已經可以直接用 setOnTintColor:、setTintColor: 與 thumbTintImage 來客製,不一定非得自己刻一個子類別。

  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved