swift版本:
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var textFields1: UITextField!
@IBOutlet weak var textFields2: UITextField!
@IBOutlet weak var resultLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
@IBAction func clickBtn(_ sender: UIButton) {
这种方法可行
// let str1 : NSInteger = (Int)(self.textFields1.text!)!
// let str2 : NSInteger = (Int)(self.textFields2.text!)!
第二种方法:
let str3 : NSInteger = (self.textFields1.text as NSString).integerValue
let str4 : NSInteger = (self.textFields2.text! as NSString).integerValue
//str3报错误: Cannot convert value of type 'String?' to type 'NSString' in coercion(强制)
self.resultLabel.text = String.init(format: "%zd", (str1 + str2)
)
}
oc版本:
@interface ViewController ()
@property (weak, nonatomic) IBOutlet UITextField *textField1;
@property (weak, nonatomic) IBOutlet UITextField *textFiled2;
@property (weak, nonatomic) IBOutlet UILabel *resultLabel;
@end
@implementation ViewController
- (IBAction)btn:(id)sender {
NSLog(@"aaa");
NSString *str1 = self.textField1.text;
NSString *str2 = self.textFiled2.text;
NSInteger num1 = str1.integerValue;
NSInteger num2 = str2.integerValue;
NSInteger result = num1 + num2;
// self.resultLabel.text = @(result).description;
self.resultLabel.text = [NSString stringWithFormat:@"%zd",result];
}
网友评论