【问题标题】:Add a Button in UIView on Tapped Point在点击点的 UIView 中添加一个按钮
【发布时间】:2009-10-01 07:33:56
【问题描述】:

您好,我正在尝试在用户点击屏幕的位置添加一个按钮。

这是我的 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 text[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];

【问题讨论】:

    标签: iphone uiview touch


    【解决方案1】:

    你得到这些值是因为你使用了 %i。

    firstTouch.x 和 .y 值实际上是浮点数,因此您应该在 NSLog 中使用 %f。

    对于添加按钮,您每次都必须分配一个新按钮(专家,如果我错了,请纠正我)。

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

    哦,是的,您可以在 touchBegan 方法本身中获取 firstTouch.x 和 firstTouch.y 并在此处添加一个按钮。

    【讨论】:

    • 我遇到了一个新问题,你能看看吗?
    【解决方案2】:

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

    此外,这些点表示为浮点数而不是整数,因此请使用 %f 而不是 %i


    回应您的新“问题”:您似乎过度释放了 newButton。记住规则……如果你通过 alloc、new 或 copy 获取对象,那么你需要释放它。如果没有,那么你没有。因此,您的应用程序崩溃了,因为您过度释放了该按钮。删除 [newButton release] 应该没问题...

    【讨论】:

    • 感谢您的回复,我遇到了一个新问题,您能看看吗?
    猜你喜欢
    • 1970-01-01
    • 2018-06-02
    • 2011-08-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-22
    • 2020-10-22
    相关资源
    最近更新 更多