2009-10-01 94 views
1

嗨即时尝试添加一个按钮,在用户点击屏幕上的点。在UIView点击点添加按钮

这里是我的UIView文件

- (void)drawRect:(CGRect)rect { 
    // Drawing code 
    NSLog(@"drawRect, %i, %i", firstTouch.x, firstTouch.y); 
    [tagButton drawRect:CGRectMake(firstTouch.x, firstTouch.y, 100, 200)]; 
    [self addSubview:tagButton]; 
} 

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

    [self setNeedsDisplay]; 
} 

的代码,这是从日志firstTouch

2009-10-01 17:27:23.743文[2521:207]的drawRect,0,1080311808

我该如何获得触摸的x,y点,并在该点上创建一个uibutton?

任何帮助,将不胜感激,谢谢


这就是我想出,其添加的按钮视图。但是当我弹出这个视图时,它会崩溃。我似乎无法找到任何问题。任何人都可以看到问题是什么?

UIButton *newButton = [UIButton buttonWithType:UIButtonTypeRoundedRect]; 
     [newButton setFrame:CGRectMake(self.firstTouch.x, self.firstTouch.y, width, 17)]; 
     [newButton setTitle:[textField text] forState:UIControlStateNormal]; 
     [newButton setFont:[UIFont boldSystemFontOfSize:12]]; 
     [newButton setShowsTouchWhenHighlighted:YES]; 
     [newButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal]; 
     [newButton setTitleShadowColor:[UIColor blackColor] forState:UIControlStateNormal]; 
     [newButton setContentHorizontalAlignment:UIControlContentHorizontalAlignmentCenter]; 
     [newButton setContentVerticalAlignment:UIControlContentVerticalAlignmentCenter]; 
     [newButton setBackgroundColor:[UIColor clearColor]]; 

     UIImage *bgImg = [[UIImage imageNamed:@"button_greyblue.png"] stretchableImageWithLeftCapWidth:15.0 topCapHeight:0.0]; 
     [newButton setBackgroundImage:bgImg forState:UIControlStateNormal]; 


     [self setTagButton:newButton]; 
     [self.view addSubview:tagButton]; 
     [newButton release]; 

回答

0

因为您使用的是%i,所以您会得到这些值。

firstTouch.x和.y值实际上是浮动的,所以你应该在NSLog中使用%f。

添加一个按钮,你将不得不每次分配一个新的按钮(专家,如果我错了,请纠正我)。

除此之外,其余代码看起来足以在点击点上添加按钮。

哦,是的,你可以在touchBegan方法本身获得firstTouch.x和firstTouch.y并在那里添加一个按钮。

+0

我遇到了一个新问题,你可以请看看吗? – vicky 2009-10-02 07:22:57

0

我不认为你想直接调用drawRect。在touchesBegan捕获touchLocation的同时,仍然在touchesBegan更新tagButton的框架。有一个称为MoveMe的示例应用程序,Apple提供的应用程序非常简单,有助于说明这一点。

此外,这些点表示为浮动不是整数所以用%f,而不是%I


到您的新“问题”回应:你似乎是在释放newButton。记住规则......如果你通过alloc,new或copy来获得对象,那么你需要释放它。如果没有,那么你不。所以你的应用程序崩溃,因为你过度释放该按钮。删除[newButton发布]和东西应该很好...

+0

感谢您的回复,我遇到了一个新问题,您可以请看看吗? – vicky 2009-10-02 07:23:46