UIButton 切换功能表现得很奇怪

发布于 2024-10-22 04:32:10 字数 1170 浏览 8 评论 0原文

我尝试用 UIButton 制作一个菜单,我只想一次只能选择一个按钮。女巫意味着当我选择一个按钮时,它会自动取消选择另一个按钮。但它的表现很奇怪,我不明白为什么。

当我从菜单中选择一个按钮时,它会变成红色,当我选择另一个按钮时,它们都是红色的,但我必须在第一个按钮上单击两次才能将其变为黑色,第二个按钮也是如此。问题是当我单击第二个按钮时,第一个按钮应该变成黑色而不是保持红色。

当使用 addTarget 按下按钮时会调用此函数。

    - (void)putInSelectedMode:(id)sender {
    NSLog(@"[%d] %s => %s", __LINE__, __FUNCTION__, __FILE__);
    if ([sender isKindOfClass:[UIButton class]]) {
        sender = (UIButton*)sender;
        if ([sender isSelected])
        {
            [sender setSelected:NO];
            [[sender layer] setShadowColor:[[UIColor clearColor] CGColor]];
            [[sender layer] setBorderWidth:0.0f];
        }
        else {

            UIButton *btn = nil;
            NSArray *subviews = [self subviews];

            for (btn in subviews) {
                if ([btn isKindOfClass:[UIButton class]]) {
                    [btn setSelected:NO];
                }
            }

            [[sender layer] setBorderWidth:5.0f];
            [[sender layer] setBorderColor:[[UIColor redColor] CGColor]];
            [[sender layer] setOpaque:NO];
            [sender setSelected:YES];
        }
    }
}

I try to make a menu with UIButton and I just want to be able to select only one button at the time. Witch means when I select a button it's automatically deselect the other one. But it's acting weird and i don't understand why.

When I select a button from the menu it's became red and when I select a another one they are both red but I have to click 2 times on the fist button to put it black and it the same thing for the second button. The problem is when I click on the second button the first should has become black instead of stay red.

This function is called when a button is pressed with addTarget.

    - (void)putInSelectedMode:(id)sender {
    NSLog(@"[%d] %s => %s", __LINE__, __FUNCTION__, __FILE__);
    if ([sender isKindOfClass:[UIButton class]]) {
        sender = (UIButton*)sender;
        if ([sender isSelected])
        {
            [sender setSelected:NO];
            [[sender layer] setShadowColor:[[UIColor clearColor] CGColor]];
            [[sender layer] setBorderWidth:0.0f];
        }
        else {

            UIButton *btn = nil;
            NSArray *subviews = [self subviews];

            for (btn in subviews) {
                if ([btn isKindOfClass:[UIButton class]]) {
                    [btn setSelected:NO];
                }
            }

            [[sender layer] setBorderWidth:5.0f];
            [[sender layer] setBorderColor:[[UIColor redColor] CGColor]];
            [[sender layer] setOpaque:NO];
            [sender setSelected:YES];
        }
    }
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文