获取superview objective-c中的CGRect位置

获取superview objective-c中的CGRect位置,objective-c,cocoa-touch,Objective C,Cocoa Touch,我想打印出CGRect的x坐标。rect的x,y坐标设置为用户触摸的位置,如下所示: - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event { UITouch *touch = [[event allTouches]anyObject]; startPoint = [touch locationInView:self]; } - (void)drawRect:(CGRect)rect { ctx

我想打印出CGRect的x坐标。rect的x,y坐标设置为用户触摸的位置,如下所示:

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    UITouch *touch = [[event allTouches]anyObject];
    startPoint = [touch locationInView:self];
}

- (void)drawRect:(CGRect)rect
{
    ctx = UIGraphicsGetCurrentContext();
    jrect = CGRectMake(startPoint.x, startPoint.y, 100, 100);
    CGContextAddRect(ctx, jrect);
    CGContextFillPath(ctx);
}
我可以打印出起始点,但如果我打印出CGRect的坐标,我会尝试这样做:

int jrectX = lroundf(CGRectGetMinX(jrect));

xlabel.text = [NSString stringWithFormat:@"x: %i", jrectX];

但它返回的数字毫无意义,有时它们的左边比右边大。代码有什么问题吗

CGRect是一个具有四个CGFloat属性的结构:x、y、width和height

要从CGRect打印x值,请执行以下操作:

[NSString stringWithFormat:@"%f", rect.x]
要打印整个rect,有一个方便的功能:

NSStringFromCGRect(rect)
您在上面遇到了问题,因为您将x值存储到int中,然后对其使用浮点舍入函数。因此,它应该是:

CGFloat jrectX = CGRectGetMinX(jrect);
。除非您正在进行旋转变换,否则只需使用:

CGFloat jrectX = jrect.origin.x;
h博士

在其他viewController中使用它

- (void)viewDidLoad
{
    DR *drr=[[DR alloc] initWithFrame:CGRectMake(0, 0, 320, 460)];
    [drr setBackgroundColor:[UIColor greenColor]];

    [self.view addSubview:drr];

    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
}

更新了答案,其中提到了CGRectGetMinX与rect.origin.x的关系
- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
         xlabel=[[UILabel alloc] initWithFrame:CGRectMake(0, 0, 100, 100)];
        [self addSubview:xlabel];
        // Initialization code
    }
    return self;
}

// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect
{
    ctx = UIGraphicsGetCurrentContext();
    jrect = CGRectMake(startPoint.x, startPoint.y, 100, 100);

    CGContextAddRect(ctx, jrect);
    CGContextFillPath(ctx);
    // Drawing code
}

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    UITouch *touch = [[event allTouches]anyObject];
    startPoint = [touch locationInView:self];

    int jrectX = lroundf(CGRectGetMinX(jrect));

    NSLog(@"jrectX --------------");
    xlabel.text = [NSString stringWithFormat:@"x: %i", jrectX];
    [self setNeedsDisplay];
}

@end
- (void)viewDidLoad
{
    DR *drr=[[DR alloc] initWithFrame:CGRectMake(0, 0, 320, 460)];
    [drr setBackgroundColor:[UIColor greenColor]];

    [self.view addSubview:drr];

    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
}