You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Xcode 14 如何为10×10按钮网格添加标识以实现交互操作

为10×10按钮网格添加标识并实现交互操作

给你几个实用的方案,帮你给每个按钮加标识,实现点击隐藏、修改颜色等操作:

方案一:利用UIButton的tag属性

UIButton自带的tag属性可以用来标记每个按钮,你可以把按钮的序号(0-99)赋值给tag,点击时就能直接识别目标按钮。

修改代码步骤:

  1. 在createButton方法中设置tag并添加点击事件:
func createButton(xPos: Int, yPos:Int, colour: String, title: String) {
    let gridButton = UIButton(frame: CGRect(x: xPos, y: yPos, width: 30, height: 30))
    gridButton.configuration = plainButtonConfig(colour: colour)
    // 将按钮序号设为tag
    gridButton.tag = Int(title)!
    // 绑定点击事件
    gridButton.addTarget(self, action: #selector(buttonTapped(_:)), for: .touchUpInside)
    view.addSubview(gridButton)
}
  1. 实现点击事件的处理方法:
@objc func buttonTapped(_ sender: UIButton) {
    let buttonIndex = sender.tag
    print("点击了第\(buttonIndex)个按钮")
    
    // 示例:隐藏点击的按钮
    sender.isHidden = true
    
    // 示例:修改按钮背景色
    sender.configuration?.baseBackgroundColor = .red
}

方案二:将按钮存入数组统一管理

如果担心tag和其他控件冲突,或者需要批量操作按钮,把所有按钮存入数组是更稳妥的方式。

修改代码步骤:

  1. 在类中声明一个数组用于存储按钮:
var buttonGrid: [UIButton] = []
  1. 调整createButton方法,让它返回创建好的按钮:
func createButton(xPos: Int, yPos:Int, colour: String, title: String) -> UIButton {
    let gridButton = UIButton(frame: CGRect(x: xPos, y: yPos, width: 30, height: 30))
    gridButton.configuration = plainButtonConfig(colour: colour)
    gridButton.addTarget(self, action: #selector(buttonTapped(_:)), for: .touchUpInside)
    return gridButton
}
  1. 在createButtonGrid中把按钮加入数组:
func createButtonGrid(colourArray: Array<String>) {
    let spacing = 35
    var xPos = 25
    var yPos = 150
    
    for i in 0...99 {
        let button = createButton(xPos:xPos, yPos: yPos, colour: colourArray[i] , title: String(i))
        buttonGrid.append(button)
        view.addSubview(button)
        
        xPos += spacing
        
        // 优化换行逻辑:每10个按钮自动换行
        if (i + 1) % 10 == 0 {
            xPos = 25
            yPos += spacing
        }
    }
}
  1. 点击事件中可以通过数组索引或直接操作sender:
@objc func buttonTapped(_ sender: UIButton) {
    if let index = buttonGrid.firstIndex(of: sender) {
        print("点击了第\(index)个按钮")
    }
    
    // 示例操作:修改按钮标题颜色
    sender.configuration?.titleTextAttributesTransformer = UIConfigurationTextAttributesTransformer { incoming in
        var outgoing = incoming
        outgoing.foregroundColor = .white
        return outgoing
    }
}

额外优化:简化换行判断逻辑

你原来的换行判断写了一堆i == 9 || i == 19...,可以用(i + 1) % 10 == 0替代,代码更简洁,后续修改网格大小也更方便。

内容的提问来源于stack exchange,提问作者thefan12345

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.17 06:50:23