Avatar
Kishikawa Katsumi 3/2/2022 8:31 PM
Objective-Cは self.signInButton[self signInButton]; のシンタックスシュガーなので、 self.signInButton.frame = CGRectMake(20, self.view.frame.size.height - 50 - self.view.safeAreaInsets.bottom, self.view.frame.size.width * 0.9, 50); self.signInButton.layer.cornerRadius = self.signInButton.frame.size.height / 2; [self.signInButton addTarget:self action:@selector(handlePress:) forControlEvents:UIControlEventTouchUpInside]; ^ の行の self.signInButton は全部 [self signInButton]; となるので、毎回新しいボタンが生成されてそれに対して設定しているので、全部無駄になっています。 Swiftのコードと同等にするにはまずヘッダファイルにプロパティの定義がなければ次のように追加してください。 @interface WelcomeViewController () @property (nonatomic) UIButton *signInButton; @end 自動的に _signInButton という変数が追加されるので、 getterメソッドを次のように書き換えてください。 - (UIButton *)signInButton { if (!_signInButton) { UIButton *button = [[UIButton alloc] init]; button.backgroundColor = [UIColor systemRedColor]; button.layer.borderWidth = 2; button.clipsToBounds = YES; [button setTitle:@"Apple IDでログイン" forState:UIControlStateNormal]; [button setTitleColor:[UIColor systemBackgroundColor] forState:UIControlStateNormal]; _signInButton = button; } return _signInButton; }
happy 1
8:32 PM
全体のコードは次のようになります。 @interface WelcomeViewController : UIViewController @property (nonatomic) UIButton *signInButton; @end @implementation WelcomeViewController - (UIButton *)signInButton { if (!_signInButton) { UIButton *button = [[UIButton alloc] init]; button.backgroundColor = [UIColor systemRedColor]; button.layer.borderWidth = 2; button.clipsToBounds = YES; [button setTitle:@"Apple IDでログイン" forState:UIControlStateNormal]; [button setTitleColor:[UIColor systemBackgroundColor] forState:UIControlStateNormal]; _signInButton = button; } return _signInButton; } - (void)viewDidLoad { [super viewDidLoad]; self.title = @"タイトル"; self.view.backgroundColor = [UIColor systemGreenColor]; [self.view addSubview:self.signInButton]; } - (void)viewDidLayoutSubviews { [super viewDidLayoutSubviews]; self.signInButton.frame = CGRectMake(20, self.view.frame.size.height - 50 - self.view.safeAreaInsets.bottom, self.view.frame.size.width * 0.9, 50); self.signInButton.layer.cornerRadius = self.signInButton.frame.size.height / 2; [self.signInButton addTarget:self action:@selector(handlePress:) forControlEvents:UIControlEventTouchUpInside]; } - (void)handlePress: (UIButton *) sender { printf("Button pressed!"); } @end
yoshi 1