返回介绍

iOS 学习笔记(三)UISlider 与 UISwitch 控件

发布于 2025-02-28 13:01:40 字数 2876 浏览 0 评论 0 收藏 0

1 首先我们还是创建一个 Single View Application,然后打开 MainStoryboard_iphone.storyboard,在 IB 中添加一个 UISlider 控件和一个 Label,这个 Label 用来显示 Slider 的值。

选中新加的 Slider 控件,打开 Attribute Inspector,修改属性值,设置最小值为 0,最大值为 100,当前值为 0.5,并确保勾选上 Continuous,如下图:

接着我们放上 UISwitch 控件,就是很像开关的那种控件,它只有两个状态:on 和 off,全都放上去效果就是这样的:

2.好了我们开始写代码喽:ViewController.h:

#import <UIKit/UIKit.h>

@interface ViewController : UIViewController{
    UILabel *sliderlabel;
    UISwitch *leftSwitch;
    UISwitch *rightSwitch;
}

@property (nonatomic,retain) IBOutlet UILabel *sliderlabel;
@property (nonatomic,retain) IBOutlet UISwitch *leftSwitch;
@property (nonatomic,retain) IBOutlet UISwitch *rightSwitch;

- (IBAction)sliderChanged:(id)sender;
- (IBAction)switchChanged:(id)sender;
@end

接着是实现 ViewController.m:

#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController
@synthesize sliderlabel;
@synthesize leftSwitch;
@synthesize rightSwitch;

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone) {
        return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
    } else {
        return YES;
    }
}

- (IBAction)sliderChanged:(id)sender{
    UISlider *slider=(UISlider*)sender;
    int progressAsInt=(int)(slider.value+0.5f);
    NSString *newText=[[NSString alloc] initWithFormat:@"%d",progressAsInt];
    sliderlabel.text=newText;
    [newText release];
    NSLog(@"%d",progressAsInt);
}

- (IBAction)switchChanged:(id)sender{
    UISwitch *whichSwich=(UISwitch *)sender;
    BOOL setting=whichSwich.isOn;
    [leftSwitch setOn:setting animated:YES];
    [rightSwitch setOn:setting animated:YES];
}

- (void)dealloc{
    [sliderlabel release];
    [leftSwitch release];
    [rightSwitch release];
    [super dealloc];
}
@end

3.剩下的就是连接操作和输出口:

将 slider 控件的 value changed 事件与 sliderChanged 方法连接在一起,将 swich 控件的 value changed 事件与 swichChanged 方法连接在一起,当然还要把 lable 控件和 swich 控件的输出与 ViewController 的相应控件接口连接在一起。

最终实现的效果如下面两张图:

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文