Chào mừng đến với Diễn đàn lập trình - Cộng đồng lập trình.
Kết quả 1 đến 3 của 3
  1. #1
    Ngày tham gia
    Sep 2015
    Bài viết
    0

  2. #2

    Cách ép kiểu trong Objective C?

    Mã:
    #import <UIKit/UIKit.h>
    
    @interface ViewController : UIViewController
    @property (strong, nonatomic) IBOutlet UITextField *txtOperand1;
    @property (strong, nonatomic) IBOutlet UITextField *txtOperand2;
    @property (strong, nonatomic) IBOutlet UILabel *lblResult;
    - (IBAction)resultAdd;
    - (IBAction)resultSubtract;
    - (IBAction)resultMultiply;
    - (IBAction)resultDivide;
    
    
    @end
    Mã:
    #import "ViewController.h"
    
    @interface ViewController ()
    
    @end
    
    @implementation ViewController
    @synthesize txtOperand1, txtOperand2, lblResult;
    
    - (void)viewDidLoad
    {
        [super viewDidLoad];
     // Do any additional setup after loading the view, typically from a nib.
    }
    
    - (void)didReceiveMemoryWarning
    {
        [super didReceiveMemoryWarning];
        // Dispose of any resources that can be recreated.
    }
    
    - (IBAction)resultAdd {
    }
    
    - (IBAction)resultSubtract {
    }
    
    - (IBAction)resultMultiply {
    }
    
    - (IBAction)resultDivide {
    }
    
    @end
    Mình đang làm 1 cái máy tính đơn giản với 2 text field là txtOperand1 và txtOperand2 và kết quả sẽ in ra lblResult.

    số được lấy ra từ txtOperand1 và txtOperand2 để làm phép tính rồi in kết quả ra label, mình ko biết convert kiểu gì. Mọi người chỉ giúp mình với. Thanks

  3. #3
    Ngày tham gia
    Sep 2015
    Bài viết
    0
    - Đầu tiên bạn cần lấy giá trị từ 2 textfield ra và chuyển sang kiểu integer:
    Mã:
    NSInteger value1 = [self.txtOperand1.text integerValue];
    NSInteger value2 = [self.txtOperand2.text integerValue];
    - Tính tổng/hiệu/tích/thương:
    Mã:
    NSInteger tong = value1 + value2;
    NSInteger hieu = value1 - value2;
    NSInteger tich = value1*value2;
    CGFloat thuong = (CGFloat)value1/(CGFloat)value2;
    ;
    - Cuối cùng bạn gán giá trị vào label:
    Mã:
    self.lblResult.text = [NSString stringWithFormat:@"Tong:%d", tong];
    self.lblResult.text = [NSString stringWithFormat:@"Hieu:%d", hieu];
    self.lblResult.text = [NSString stringWithFormat:@"Tich:%d", tich];
    self.lblResult.text = [NSString stringWithFormat:@"Thuong:%.2f", thuong];
    Bạn nên tìm thêm tài liệu về datatype trong Objective-C để nghiên cứu thêm.
    Chúc bạn thành công [IMG]images/smilies/smile.png[/IMG]

 

 

Quyền viết bài

  • Bạn Không thể gửi Chủ đề mới
  • Bạn Không thể Gửi trả lời
  • Bạn Không thể Gửi file đính kèm
  • Bạn Không thể Sửa bài viết của mình
  •