在Xcode中使用tap功能制作图像的最佳方法?

bme*_*nde 2 xcode objective-c uibutton uiimage

我正在尝试制作一个游戏,如果你点击一个小的50X53图像显示你点击它的地方,我开始使50x53图像的东西一个按钮,当你触摸按钮按钮的背景变为红色(到模拟在那里添加了一个图像)所以这里我在viewController上有大约48个按钮(6X8),每当我按下其中一个按钮时,背景变为红色,确定简单,但现在我想做的是拥有UI完全空白(您看不到任何按钮)然后当您按下给定区域时,会在您按下的那个小空间中弹出一个图像.我想而不是做

-(IBAction)imagePressed
{
sender.background=[UIColor redColor];
}


-(IBAction)imagePressedAgain
{
sender.background=[UIColor whiteColor];
}
Run Code Online (Sandbox Code Playgroud)

我打算做点什么

-(IBAction)imagePressed
{
sender.image=@"whateverImage.png";
//I know this isn't the right syntax to change a buttons image (and i don't even know if i can change a buttons image) but anyways i was going to try to here
}
-(IBAction)imagePressedAgain
{
sender.image=@"imageThatIsJustAWhiteBackground";
}
Run Code Online (Sandbox Code Playgroud)

所以我试着这样做,然后想到自己,嗯,也许我不应该这样做,我应该使用一堆小UIImageViews并将它们全部放在interfaceBuilder上?喜欢而不是在屏幕上有48个按钮,我会有48个UIImageViews?然后我想我会为每个添加一个轻拍手势识别器?或者我应该坚持我的旧计划并更改按钮图像?

(o,顺便说一句,我不能让图像与用户在屏幕上触摸手指的位置完全成比例,我必须将它放在有组织的网格中,所以我必须有48个.)

eze*_*DFM 5

如果你想按照你所描述的(6x8)保持类似网状的布置,你可以做如下的事情:

 NSMutableArray *buttons = [[NSMutableArray alloc] init];

// Loop through and create 48 buttons at 50 x 53
for(int i = 0; i < 48; i++)
{
    UIButton *pressMe = [UIButton buttonWithType:UIButtonTypeCustom];

    [buttons addObject:pressMe];
    pressMe.frame = CGRectMake(0, 0, 50, 53);
    // Set background image for when button is selected
    [pressMe setBackgroundImage:[UIImage imageNamed:@"selectedImage.png"] forState:UIControlStateSelected];
    // Add target to toggle selected state of button
    [pressMe addTarget:self action:@selector(buttonPressed:) forControlEvents:UIControlEventTouchUpInside];
}

int col = 0;
int row = 0;
int maxPerRow = 6;
float spacingHorizontal = 50;
float spacingVertical = 53;

for(UIButton *view in buttons)
{
    // position buttons in 6 x 8 grid
    view.frame = CGRectMake(col * spacingHorizontal, row * spacingVertical, view.frame.size.width, view.frame.size.height);
    [self.view addSubview:view];

    if(col % maxPerRow == maxPerRow-1)
    {
        col = 0;
        row++;
    }
    else
    {
        col++;
    }
}
Run Code Online (Sandbox Code Playgroud)

您可以看到重要的部分是为按钮设置所选图像.这样,您可以在点按按钮时显示自定义图像.这是我测试的屏幕上限.如果你想我可以给你项目文件.

在此输入图像描述

  • 哈,不用担心,按照自己的意愿使用!我在这里添加了一个链接到源代码以供将来参考.http://www.zen-sign.com/source/StackOverflowTestApp.zip (2认同)