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

Swift新手求助:实现按钮按下变色、松开还原的效果

Swift新手求助:实现按钮按下变色、松开还原的效果

嗨~别着急,这个需求其实很好实现,我给你两种实用方案,你可以根据自己的iOS版本来选:

方案一:传统触摸事件监听(兼容所有iOS版本)

这种方法适合所有iOS版本,通过监听按钮的触摸事件来切换颜色,逻辑清晰易懂:

  1. 先定义按钮的初始颜色和按下时的颜色
  2. 给按钮添加touchDown(按下)、touchUpInside(松开在按钮内)、touchUpOutside(松开在按钮外)、touchCancel(触摸被打断)这几个事件的监听
  3. 在对应的方法里修改按钮背景色

完整代码示例:

import UIKit

class ViewController: UIViewController {
    // 自定义按钮的初始颜色和高亮颜色
    let originalBgColor = UIColor.systemBlue
    let highlightedBgColor = UIColor.systemBlue.withAlphaComponent(0.7)
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        // 创建按钮并设置基础样式
        let actionButton = UIButton(type: .system)
        actionButton.setTitle("点击测试", for: .normal)
        actionButton.backgroundColor = originalBgColor
        actionButton.setTitleColor(.white, for: .normal)
        actionButton.layer.cornerRadius = 8 // 可选:给按钮加圆角
        actionButton.frame = CGRect(x: 60, y: 250, width: 240, height: 50)
        
        // 添加触摸事件监听
        actionButton.addTarget(self, action: #selector(buttonPressed), for: .touchDown)
        actionButton.addTarget(self, action: #selector(buttonReleased), for: [.touchUpInside, .touchUpOutside, .touchCancel])
        
        view.addSubview(actionButton)
    }
    
    // 按钮按下时切换到高亮颜色
    @objc func buttonPressed(_ sender: UIButton) {
        sender.backgroundColor = highlightedBgColor
    }
    
    // 按钮松开或触摸中断时恢复原颜色
    @objc func buttonReleased(_ sender: UIButton) {
        sender.backgroundColor = originalBgColor
    }
}

为什么要监听touchUpOutside和touchCancel?因为如果用户手指滑出按钮范围,或者突然有来电打断触摸,按钮也能恢复原色,不会一直停留在按下状态~

方案二:用UIButton.Configuration(iOS 15+ 更简洁)

如果你开发的App只需要兼容iOS15及以上版本,用苹果提供的Button Configuration会更省心,不用手动写事件监听,系统自动处理状态切换:

import UIKit

class ViewController: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()
        
        // 创建按钮配置
        var buttonConfig = UIButton.Configuration.filled()
        buttonConfig.title = "点击测试"
        buttonConfig.baseBackgroundColor = .systemBlue // 正常状态背景色
        buttonConfig.highlightedBackgroundColor = .systemBlue.withAlphaComponent(0.7) // 按下状态背景色
        buttonConfig.cornerStyle = .medium // 可选:设置圆角样式
        
        // 用配置创建按钮
        let actionButton = UIButton(configuration: buttonConfig)
        actionButton.frame = CGRect(x: 60, y: 250, width: 240, height: 50)
        
        view.addSubview(actionButton)
    }
}

如果之前你试的方法没用,可以检查下是不是漏加了触摸事件,或者把backgroundColor和tintColor搞混了(有些按钮样式会用tintColor控制颜色,不过大部分自定义按钮用backgroundColor更直接)。

备注:内容来源于stack exchange,提问作者humble

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.17 10:07:59