我正在閱讀The Big Nerd Ranch Guide(第4版,想要Objective C)的iOS編程第5章,我遵循子類化UIView
類的說明並添加了子視圖在AppDelegate
,事情是子視圖不捕獲touchesBegan
事件,但AppDelegate
捕捉信號。touchesBegan被AppDelegate捕獲而不是UIView的子類
didFinishLaunchingWithOptions
方法在AppDelegate
:
self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
[self.window setRootViewController:[UIViewController alloc]];
CGRect firstFrame = self.window.bounds;
HypnosisView *firstView = [[HypnosisView alloc] initWithFrame:firstFrame];
[self.window addSubview:firstView];
[firstView becomeFirstResponder];
self.window.backgroundColor = [UIColor whiteColor];
[self.window makeKeyAndVisible];
return YES;
爲HypnosisView
兩個初始化方法中,子類UIView
定義如下:
#import "HypnosisView.h"
@interface HypnosisView()
@property (strong, nonatomic) UIColor *circleColor;
@end
@implementation HypnosisView
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
CGRect bounds = self.bounds;
CGRect frame = self.frame;
// Figure out the center of the bounds rectangle
CGPoint center;
center.x = frame.origin.x + frame.size.width/2.0;
center.y = frame.origin.y + frame.size.height/2.0;
// The largest circle will circumscribe the view
float maxRadius = hypot(bounds.size.width, bounds.size.height)/2.0;
UIBezierPath *path = [[UIBezierPath alloc] init];
for (float currentRadius = maxRadius; currentRadius > 0; currentRadius -= 20) {
[path moveToPoint:CGPointMake(center.x + currentRadius, center.y)];
[path addArcWithCenter:center
radius:currentRadius
startAngle:0.0
endAngle:M_PI * 2
clockwise:YES];
}
// Configure line with to 10 points
path.lineWidth = 10;
// Configure the drawing color to light gray
[self.circleColor setStroke];
// Draw the line!
[path stroke];
}
- (instancetype)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
// All HypnosisViews start with a clear background color
self.backgroundColor = [UIColor clearColor];
self.circleColor = [UIColor lightGrayColor];
self.userInteractionEnabled = YES;
}
return self;
}
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
NSLog(@"%@ was touched", self);
}
如果代碼來自該書,則不應將其發佈到此處。這是他們的知識產權。 –