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

如何在请求接口后默认选中UIKit栈视图的首个按钮?

UIKit StackView 实现首个按钮默认选中并变色

核心步骤

  • 提前定义按钮的选中/未选中样式(文字颜色、背景色等)
  • 从服务器获取数据后,动态生成按钮并添加到StackView
  • 按钮全部创建完成后,主动将第一个按钮设为选中状态并更新样式

代码实现示例

import UIKit

class ViewController: UIViewController {
    private let stackView = UIStackView()
    private var buttons = [UIButton]()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        setupStackView()
        fetchButtonData()
    }
    
    // 初始化StackView布局
    private func setupStackView() {
        stackView.axis = .horizontal
        stackView.spacing = 8
        stackView.translatesAutoresizingMaskIntoConstraints = false
        view.addSubview(stackView)
        
        NSLayoutConstraint.activate([
            stackView.centerXAnchor.constraint(equalTo: view.centerXAnchor),
            stackView.centerYAnchor.constraint(equalTo: view.centerYAnchor)
        ])
    }
    
    // 模拟服务器获取按钮数据(替换为你的实际网络请求)
    private func fetchButtonData() {
        DispatchQueue.global().asyncAfter(deadline: .now() + 1) { [weak self] in
            guard let self = self else { return }
            // 假设服务器返回的按钮标题数组
            let serverButtonTitles = ["推荐", "热门", "最新", "收藏"]
            
            DispatchQueue.main.async {
                self.generateButtons(from: serverButtonTitles)
                // 设置第一个按钮默认选中
                self.buttons.first.map(self.selectTargetButton)
            }
        }
    }
    
    // 根据数据生成按钮并添加到StackView
    private func generateButtons(from titles: [String]) {
        // 清空旧的按钮和StackView内容
        buttons.removeAll()
        stackView.arrangedSubviews.forEach { $0.removeFromSuperview() }
        
        for title in titles {
            let button = UIButton(type: .system)
            button.setTitle(title, for: .normal)
            // 设置未选中样式
            button.setTitleColor(.darkGray, for: .normal)
            button.backgroundColor = .systemGray6
            button.layer.cornerRadius = 6
            button.clipsToBounds = true
            // 设置选中样式(也可以在selectTargetButton里统一设置)
            button.setTitleColor(.white, for: .selected)
            button.backgroundColor = .systemBlue
            button.addTarget(self, action: #selector(buttonTapHandler(_:)), for: .touchUpInside)
            
            stackView.addArrangedSubview(button)
            buttons.append(button)
        }
    }
    
    // 按钮点击事件处理
    @objc private func buttonTapHandler(_ sender: UIButton) {
        // 先取消所有按钮选中状态
        buttons.forEach { $0.isSelected = false }
        // 选中当前点击的按钮
        selectTargetButton(sender)
    }
    
    // 统一处理按钮选中逻辑
    private func selectTargetButton(_ button: UIButton) {
        button.isSelected = true
        button.backgroundColor = .systemBlue
        button.setTitleColor(.white, for: .selected)
    }
}

注意事项

  • 网络请求完成后必须切换到主线程更新UI,否则会出现异常
  • 可以根据需求自定义按钮的选中样式,比如添加边框阴影、调整字体大小等
  • 使用weak self避免网络请求回调中出现循环引用

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 23:10:56