我正在学习使用XCode 4.5.2构建iPhone应用程序,我发现了一些奇怪的东西.正如您在地址
http://i.stack.imgur.com/purI8.jpg处所看到的,其中一个按钮内的文本未显示在iOS6模拟器中.我还尝试在0和 – 的相同行中移动Enter按钮,但该行的所有三个按钮中的文本都消失了.任何人都知道这个问题的原因是什么以及如何解决?这是代码:
#import "CalculatorViewController.h" #import "CalculatorBrain.h" @interface CalculatorViewController() @property (nonatomic) BOOL userIsInTheMiddleOfEnteringANumber; @property (nonatomic,strong) CalculatorBrain *brain; @end @implementation CalculatorViewController @synthesize display; @synthesize userIsInTheMiddleOfEnteringANumber; @synthesize brain = _brain; - (CalculatorBrain *)brain { if (!_brain) _brain = [[CalculatorBrain alloc] init]; return _brain; } - (IBAction)digitPressed:(UIButton *)sender { NSString *digit = [sender currentTitle]; if (self.userIsInTheMiddleOfEnteringANumber) { self.display.text = [self.display.text stringByAppendingString:digit]; } else { self.display.text = digit; self.userIsInTheMiddleOfEnteringANumber = YES; } } - (IBAction)enterPressed { [self.brain pushOperand:[self.display.text doubleValue]]; self.userIsInTheMiddleOfEnteringANumber = NO; } - (IBAction)operationPressed:(UIButton *)sender { if (self.userIsInTheMiddleOfEnteringANumber) [self enterPressed]; NSString *operation = [sender currentTitle]; double result = [self.brain performOperation:operation]; self.display.text = [NSString stringWithFormat:@"%g",result]; } @end
解决方法
根据
https://developer.apple.com/library/ios/documentation/uikit/reference/UIButton_Class/UIButton/UIButton.html#//apple_ref/doc/uid/TP40006815-CH3-SW7
- (void)setTitle:(NSString *)title forState:(UIControlState)state
设置按钮标题.
所以在你的情况下:
- (IBAction)operationPressed:(UIButton *)sender{ .... [sender setTitle:[NSString stringWithFormat:@"%g",result] forState: UIControlStateNormal]; // lets assume you want the down states as well: [sender setTitle:[NSString stringWithFormat:@"%g",result] forState: UIControlStateSelected]; [sender setTitle:[NSString stringWithFormat:@"%g",result] forState: UIControlStateHighlighted];
}