Here's my code:
这是我的代码:
#import "ViewController.h"
@implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
UIView *view1 = [[UIView alloc] initWithFrame:CGRectMake(50.0, 50.0, 0, 0)];
[self.view addSubview:view1];
}
-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
UITouch *touch = [[event allTouches] anyObject];
if([touch.view isEqual:self]) {
CGPoint point = [[touches anyObject] locationInView:self];
NSLog(@"%@",NSStringFromCGPoint(point));
self.view1.center = point;
}
}
I want to be able to access the instance "view1" of the class "UIView" from the touchesMoved method.
我希望能够从touchesMoved方法访问类“UIView”的实例“view1”。
Thanks in advance!
提前致谢!
2 个解决方案
#1
2
You can declare local variables as stated in the other answer. However, in my opinion its better to declare private properties in the anonymous category as below:
您可以按照另一个答案中的说明声明局部变量。但是,在我看来,最好在匿名类别中声明私有属性,如下所示:
#import "ViewController.h"
@interface ViewController ()
@property (nonatomic, strong) UIView *view1; // declares view1 as a private property
@end
@implementation ViewController
@synthesize view1 = _view1;
- (void)viewDidLoad
{
[super viewDidLoad];
self.view1 = [[UIView alloc] initWithFrame:CGRectMake(50.0, 50.0, 0, 0)];
[self.view addSubview:self.view1];
}
-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
UITouch *touch = [[event allTouches] anyObject];
if([touch.view isEqual:self])
{
CGPoint point = [[touches anyObject] locationInView:self];
NSLog(@"%@",NSStringFromCGPoint(point));
self.view1.center = point;
}
}
#2
0
You can make rect1
an instance variable by placing it in your .h
file. You can do something like:
您可以将rect1放在.h文件中,使其成为实例变量。你可以这样做:
@interface tempViewController : UIViewController
{
myRect *rect1;
}
Then in your .m
file you will not have to declare it again.
然后在.m文件中,您不必再次声明它。
#1
2
You can declare local variables as stated in the other answer. However, in my opinion its better to declare private properties in the anonymous category as below:
您可以按照另一个答案中的说明声明局部变量。但是,在我看来,最好在匿名类别中声明私有属性,如下所示:
#import "ViewController.h"
@interface ViewController ()
@property (nonatomic, strong) UIView *view1; // declares view1 as a private property
@end
@implementation ViewController
@synthesize view1 = _view1;
- (void)viewDidLoad
{
[super viewDidLoad];
self.view1 = [[UIView alloc] initWithFrame:CGRectMake(50.0, 50.0, 0, 0)];
[self.view addSubview:self.view1];
}
-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
UITouch *touch = [[event allTouches] anyObject];
if([touch.view isEqual:self])
{
CGPoint point = [[touches anyObject] locationInView:self];
NSLog(@"%@",NSStringFromCGPoint(point));
self.view1.center = point;
}
}
#2
0
You can make rect1
an instance variable by placing it in your .h
file. You can do something like:
您可以将rect1放在.h文件中,使其成为实例变量。你可以这样做:
@interface tempViewController : UIViewController
{
myRect *rect1;
}
Then in your .m
file you will not have to declare it again.
然后在.m文件中,您不必再次声明它。