iPhone数値反転

C++で数値反転するiPhoneアプリのサンプルコードを描いてみます。

#import “ViewController.h”

#include <memory>

using namespace std;

class NumberFactory {

public:

    int inverseInteger(int);

};

int NumberFactory::inverseInteger(int n) {

    int m = 0;

    while (n >= 1) {

        m *= 10;

        m += n % 10;

        n = n / 10;

    }

    return m;

}

@interface ViewController ()

@property (nonatomic) std::shared_ptr<NumberFactory> cppClass;

@property (nonatomic, weak) UITextField *textField;

@end

@implementation ViewController

– (void)viewDidLoad {

    [super viewDidLoad];

    

    UITextField *tf = [[UITextField alloc] initWithFrame:CGRectMake(0, 0, 100, 30)];

    tf.center = CGPointMake(CGRectGetMidX(self.view.bounds), 50);

    tf.backgroundColor = [UIColor greenColor];

    [self.view addSubview:tf];

    self.textField = tf;

    UIButton *btn = [UIButton buttonWithType:UIButtonTypeSystem];

    [btn setTitle:@”Reverse” forState:UIControlStateNormal];

    [btn sizeToFit];

    btn.center = CGPointMake(tf.center.x, tf.center.y + 50);

    [btn addTarget:self action:@selector(reverseCutin) forControlEvents:UIControlEventTouchUpInside];

    [self.view addSubview:btn];

}

– (void)reverseCutin {

    

    int original = [self.textField.text intValue];

    std::shared_ptr<NumberFactory> cppClass(new NumberFactory());

    int answer = self.cppClass->inverseInteger(original);

    UILabel *ticker = [[UILabel alloc] init];

    ticker.font = [UIFont boldSystemFontOfSize:40];

    ticker.backgroundColor = [UIColor yellowColor];

    ticker.text = [NSString stringWithFormat:@”%d”, answer];

    [ticker sizeToFit];

    ticker.center = CGPointMake(500, CGRectGetMidY(self.view.bounds) – 150);

    [self.view addSubview:ticker];

    

    [UIView animateWithDuration:0.5 animations:^{

        ticker.center = CGPointMake(CGRectGetMidX(self.view.bounds), ticker.center.y);

    }];

}

@end