1.AppDelegate.h
3.ViewController.h
4.ViewController.m
#import "ViewController.h"
@interface ViewController ()
@end
@implementation ViewController
@synthesize bilField;
@synthesize tipFieldTen;
@synthesize tipFieldFifteen;
@synthesize tipFieldTwenty;
@synthesize tipFieldCustom;
@synthesize totalFieldCustom;
@synthesize totalFieldTen;
@synthesize totalFieldFifteen;
@synthesize totalFieldTwenty;
@synthesize customPercentLabel;
@synthesize customPercentSlider;
- (void)viewDidLoad
{
[superviewDidLoad];
bilField.delegate =self;
// Do any additional setup after loading the view, typically from a nib.
}
- (void)didReceiveMemoryWarning
{
[superdidReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
-(void)awakeFromNib//当所有GUI的元素被都载入后,调用此方法。
{
[bilFieldbecomeFirstResponder];//显示用于bilField输入的键
}
-(BOOL)textFieldShouldReturn:(UITextField *)textField//用于隐藏键盘
{
[textField resignFirstResponder];
return YES;
}
-(IBAction)calculate:(id)sender
{
static BOOL toggle =YES;//标记此方法是否有用户触发
if (toggle)//如果用户从键盘输入或者滑动滑动条
{
toggle = NO;//设置标志位,此方法的下次调用将由程序触发
NSString *billFieldText = bilField.text;
float newTotal = [billFieldText floatValue];//字符串类型转化为浮点类型
float customTipPercent = customPercentSlider.value;//获得滑动条的值
if (sender==bilField)
{//判断事件是否有bilField触发
if (billFieldText.length<billTotal.length)
billTotal = [NSString stringWithFormat:@"%.02f",newTotal/10];
else
billTotal = [NSString stringWithFormat:@"%.02f",newTotal*10];
bilField.text = billTotal;//将界面上显示的文本更新为格式化后的结果
newTotal = [billTotal floatValue];//将newTotal设置为新的值
//按照10%,15%,20%三个百分比分别计算小费金额
float tenTip = newTotal*0.10;
float fifteenTip = newTotal*0.15;
float twentyTip = newTotal*0.20;
//设置Tip栏中显示的值
tipFieldTen.text = [NSString stringWithFormat:@"%0.2f",tenTip];
tipFieldFifteen.text = [NSString stringWithFormat:@"%0.2f",fifteenTip];
tipFieldTwenty.text = [NSString stringWithFormat:@"%0.2f",twentyTip];
//设置Total栏中显示的值
totalFieldTen.text = [NSString stringWithFormat:@"%0.2f",newTotal+ tenTip];
totalFieldFifteen.text = [NSString stringWithFormat:@"%0.2f",newTotal + fifteenTip];
totalFieldTwenty.text = [NSString stringWithFormat:@"%0.2f",newTotal + twentyTip];
}
else if(sender==customPercentSlider)//判断事件是否是有customPercentSlider触发的
{
int percentage = (int)(customTipPercent *100);//将滑动条的百分比转化成一个整数
customPercentLabel.text = [NSString stringWithFormat:@"%i%%",percentage];//更新标签上显示的小费百分比,以XX%的形式显示
float newSliderValue = ((float)percentage)/100;//将百分比转化成小数,并赋值给滑动条
customPercentSlider.value = newSliderValue;
customTipPercent = newSliderValue;//根据滑动条的比例更新customTipPercent的值
}
//计算customTip的值
float customTip = customTipPercent * newTotal;
tipFieldCustom.text = [NSString stringWithFormat:@"%.02f",customTip];
//更新totalFieldCustom
totalFieldCustom.text = [NSString stringWithFormat:@"%.02f",customTip + newTotal];
}
else
{
toggle = YES;
}
}
@end
运行之后:
原文:http://blog.csdn.net/eduora_meimei/article/details/21642431