下面繼續學習ios的其他控制項,這次會使用到的控制項有Slider,當然還有一些之前已經使用過的控制項Label。
這次我們不建立一個project了,當然如果你願意重新建立一個新的項目也完全可以,我們還是使用上一篇的項目Control Fun。
上一篇中,我們最後的成果如所示
1)添加Slider和Label
2)設定Slider的屬性
3)添加Label
4)為Label添加Outlet,為Slider添加Action
添加的方法很簡單,選中label,按住control鍵拖到BIDViewController.h中,在彈出的框框裡,為Outlet取一個名字叫做sliderLabel,單擊return,完成添加。
添加Action,滑鼠選中slider,按住control鍵拖到BIDViewController.h中,在彈出的框框裡,將Connection改成“Action”,為Action取一個名字叫做sliderChanged,單擊return,完成添加。
添加完的BIDViewController.h如下:
#import <UIKit/UIKit.h>@interface BIDViewController : UIViewController@property (weak, nonatomic) IBOutlet UITextField *nameField;@property (weak, nonatomic) IBOutlet UITextField *numberField;@property (weak, nonatomic) IBOutlet UILabel *sliderLabel;- (IBAction)textFieldDoneEditing:(id)sender;- (IBAction)backgroundTap:(id)sender;- (IBAction)sliderChanged:(id)sender;@endBIDViewController.m如下:
#import "BIDViewController.h"@implementation BIDViewController@synthesize nameField;@synthesize numberField;@synthesize sliderLabel;......- (IBAction)sliderChanged:(id)sender {}5)添加code
- (IBAction)sliderChanged:(id)sender { UISlider *slider = (UISlider *)sender; int progressAsInt = (int)roundf(slider.value); sliderLabel.text = [NSString stringWithFormat:@"%d", progressAsInt];}
代碼還是很好理解的,當滑塊位置發生改變時,觸發sliderChanged,在sliderChanged中,將sender轉換成UISlider對象,然後擷取滑塊位置的當前值,然後將當前值賦給label。
6)編譯運行