-1

这是我的代码:

#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;
     }
}

我希望能够从 touchesMoved 方法访问“UIView”类的实例“view1”。

提前致谢!

4

2 回答 2

2

您可以按照其他答案中的说明声明局部变量。但是,我认为最好在匿名类别中声明私有属性,如下所示:

#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;
    }
}
于 2013-01-03T23:06:35.103 回答
0

您可以rect1通过将其放在.h文件中来创建实例变量。您可以执行以下操作:

@interface tempViewController : UIViewController
{
      myRect *rect1;
}

然后在您的.m文件中,您不必再次声明它。

于 2013-01-03T22:56:45.240 回答