【发布时间】:2014-08-19 10:05:29
【问题描述】:
我是Objective-C的新手,有一点开发经验,但不多。
我目前正在学习自定义绘图、处理视图和了解视图控制器。
我只是想制作一个应用程序,当我触摸它时矩形会改变颜色。我的颜色改变部分没问题,但我目前的问题是我希望颜色只有在我触摸矩形内部时才会改变。目前发生的情况是,无论我触摸屏幕,颜色都会发生变化。
这是我的代码: NICRectangleView.m
#import "NICRectangleView.h"
@implementation NICRectangleView
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
// Initialization code
self.rectColor = [UIColor redColor];
}
return self;
}
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect
{
// Drawing code
CGRect bounds = CGRectMake(50, 50, 200, 100);
UIBezierPath *rectPath = [UIBezierPath bezierPathWithRect:bounds];
[self.rectColor setFill];
[rectPath fill];
}
-(void)setRectColor:(UIColor *)rectColor
{
_rectColor = rectColor;
[self setNeedsDisplay];
}
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
NSLog(@"%@ was touched", self);
if (self.rectColor == [UIColor redColor]) {
self.rectColor = [UIColor blueColor];
} else {
self.rectColor = [UIColor redColor];
}
}
@end
NICRectangleViewController.m:
#import "NICRectangleViewController.h"
#import "NICRectangleView.h"
@interface NICRectangleViewController ()
@end
@implementation NICRectangleViewController
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
-(void)loadView
{
NICRectangleView *rectView = [[NICRectangleView alloc]init];
self.view = rectView;
self.view.backgroundColor = [UIColor whiteColor];
}
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view.
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
还有我的 AppDelegate.m:
#import "NICAppDelegate.h"
#import "NICRectangleView.h"
#import "NICRectangleViewController.h"
@implementation NICAppDelegate
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
// Override point for customization after application launch.
NICRectangleViewController *rvc = [[NICRectangleViewController alloc]init];
self.window.rootViewController = rvc;
self.window.backgroundColor = [UIColor whiteColor];
[self.window makeKeyAndVisible];
return YES;
}
我是否认为这是因为当我将 windows rootViewController 设置为我的 RectangleViewController 时,它会自动设置它以便控制器管理的视图是全屏的?
我该如何更改?
非常感谢您阅读本文。
最好的问候,
NC
【问题讨论】:
-
看看那里:stackoverflow.com/questions/14856906/… 以了解您“触摸”的位置,并按照您的意愿行事。
标签: ios objective-c view uiviewcontroller