MST

星途 面试题库

面试题:Objective-C中如何自定义一个继承自UIButton的UI组件并复用

在Objective-C里,要求你自定义一个继承自UIButton的组件,该组件有一个特殊的点击动画效果,并且能够在多个视图控制器中复用,请描述实现步骤并给出关键代码示例。
46.3万 热度难度
编程语言Objective-C

知识考点

AI 面试

面试题答案

一键面试
  1. 创建自定义UIButton子类
    • 在Xcode中,通过File -> New -> File...,选择Cocoa Touch Class,然后继承自UIButton。假设类名为CustomButton
  2. 实现特殊点击动画效果
    • CustomButton类中重写touchesBegan:withEvent:touchesEnded:withEvent:方法。
    • touchesBegan:withEvent:方法中,开始动画,例如改变按钮的透明度、缩放等。
    • touchesEnded:withEvent:方法中,结束动画并恢复按钮的原始状态。
  3. 在多个视图控制器中复用
    • 在需要使用的视图控制器中,导入CustomButton头文件。
    • 在视图控制器的viewDidLoad方法或者其他合适的地方,创建CustomButton实例并添加到视图中。

关键代码示例:

// CustomButton.h
#import <UIKit/UIKit.h>

@interface CustomButton : UIButton

@end

// CustomButton.m
#import "CustomButton.h"

@implementation CustomButton

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    [super touchesBegan:touches withEvent:event];
    // 开始动画,例如透明度变为0.5
    self.alpha = 0.5;
}

- (void)touchesEnded:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    [super touchesEnded:touches withEvent:event];
    // 结束动画,恢复透明度为1
    self.alpha = 1;
}

@end

// ViewController.m
#import "ViewController.h"
#import "CustomButton.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    CustomButton *customButton = [CustomButton buttonWithType:UIButtonTypeCustom];
    customButton.frame = CGRectMake(100, 100, 200, 50);
    [customButton setTitle:@"Custom Button" forState:UIControlStateNormal];
    [customButton addTarget:self action:@selector(buttonTapped) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:customButton];
}

- (void)buttonTapped {
    NSLog(@"Custom button tapped");
}

@end