前面了解了iOS的基本知识,并且写了一个简单的app,从现在的文章开始就正式进入iOS的学习中了。先学习以下iOS的基本控件。
Slider控件:
- (IBAction)sliderAction:(id)sender {
UISlider *slider = (UISlider *)sender;
int progressInt = ( int )roundf(slider.value);
lableOutlet.text = [NSString stringWithFormat:@"%d",progressInt];
}
OK,编译运行,可以看到随着slider的拖动,label就会显示不同的数值。
- (IBAction)controlAction:(id)sender {
if ([sender selectedSegmentIndex ] == 0 ) {
firstImageView.hidden = YES;
secondImageview.hidden = YES;
}
else if ( [sender selectedSegmentIndex ] == 1){
firstImageView.hidden = NO;
secondImageview.hidden = YES;
}
else{
firstImageView.hidden = YES;
secondImageview.hidden = NO;
}
}
第一个if语句标示当选择第一个segment的时候,隐藏两个imageview,后面都类似功能。
2.添加3个switch到界面上,如下:
3.添加outlet和action
为3个switch添加outlet ,3个switch共用一个action,segmented control使用一个action。如何使得3个switch共用一个action看上文。添加完成之后的.h文件如下:
#import <UIKit/UIKit.h>
@interface UIExample1ViewController : UIViewController
- (IBAction)sliderAction:(id)sender;
@property (weak, nonatomic) IBOutlet UILabel *lableOutlet;
@property (weak, nonatomic) IBOutlet UISwitch *firstSwitch;
@property (weak, nonatomic) IBOutlet UISwitch *secondSwitch;
@property (weak, nonatomic) IBOutlet UISwitch *thirdSwitch;
- (IBAction)switchAction:(id)sender;
- (IBAction)controlAction:(id)sender;
@end
.m文件如下:我这里没有自动添加属性,所以我都是自己写的。不知道是什么原因导致的没有自动添加。
#import "UIExample1ViewController.h"
@interface UIExample1ViewController ()
@end
@implementation UIExample1ViewController
@synthesize lableOutlet;
@synthesize firstSwitch;
@synthesize secondSwitch;
@synthesize thirdSwitch;
.....
- (IBAction)switchAction:(id)sender {
}
- (IBAction)controlAction:(id)sender {
}
@end
实现switchAction
- (IBAction)switchAction:(id)sender {
UISwitch * whichSwitch = (UISwitch * ) sender;
BOOL seeting = whichSwitch.isOn;
[ firstSwitch setOn:seeting animated:YES];
[ secondSwitch setOn:seeting animated:YES];
[ thirdSwitch setOn:seeting animated:YES];
}
因为3个switch都关联到了这个action,如果任何一个switch改变的话,都会出发这个aciton。在该方法中,首先将sender强制转换成UISwitch类型,这样就可以使用UISwitch定义的属性了,isOn用来判断Switch的状态是打开还是关闭(Switch仅有的2种状态),最好根据触发事件的Switch状态,将另一个switch也设置成相同的状态,程序中为了方便,并没有判断到底是哪个switch触发了该Action,只是简单的将2个switch设成相同的状态而已。setOn方法是根据后面的BOOL型参数的值来设置Switch的状态是打开还是关闭(ON,OFF)。
animated是指当Switch从一种状态切换到另一种状态后,其滑块是否有活动效果,如果是YES,则滑块滑动的慢点,给人的感觉滑块是慢慢移动过去的,如果设成NO,滑块会很快地改变位置,滑动的速度很快。
运行程序可以看到,3个switch状态都是一样的,如果有一个switch改变了,其余2个也都跟着改变。
打完手工。