面试题答案
一键面试- 创建自定义UIButton子类:
- 在Xcode中,通过
File -> New -> File...
,选择Cocoa Touch Class
,然后继承自UIButton
。假设类名为CustomButton
。
- 在Xcode中,通过
- 实现特殊点击动画效果:
- 在
CustomButton
类中重写touchesBegan:withEvent:
和touchesEnded:withEvent:
方法。 - 在
touchesBegan:withEvent:
方法中,开始动画,例如改变按钮的透明度、缩放等。 - 在
touchesEnded:withEvent:
方法中,结束动画并恢复按钮的原始状态。
- 在
- 在多个视图控制器中复用:
- 在需要使用的视图控制器中,导入
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