【发布时间】:2016-12-16 23:47:44
【问题描述】:
我正在阅读 The Big Nerd Ranch Guide 的 iOS 编程第 5 章(第 4 版,想要 Objective C),我按照关于子类化 UIView 类的说明,并在 AppDelegate 中添加了子视图,这件事是子视图没有捕捉到touchesBegan 事件, 但AppDelegate 捕捉到了信号。
AppDelegate 中的didFinishLaunchingWithOptions 方法:
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);
}
【问题讨论】:
-
如果代码来自书中,你不应该在这里发布。这是他们的知识产权。
标签: ios objective-c uiview appdelegate touchesbegan