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

在Swift中,如何让AlertView内的Button宽度与TextField宽度匹配?

实现UIAlertController中TextField的leftView按钮宽度匹配TextField宽度

问题描述

在Swift开发中,给UIAlertController(实例名为returnAlert)的TextField添加了自定义UIButton作为leftView,当前按钮宽度设为固定值250,希望实现该按钮宽度与TextField宽度完全匹配。

原实现代码:

returnAlert?.addTextField(configurationHandler: { [self] (textField) in
    // Dropdown Start here
    let customDiscounTypes:[String] = ["\(PaymentCardType.MasterCard)", "\(PaymentCardType.VISA)", "\(PaymentCardType.AmericanExpress)", "\(PaymentCardType.DinnersClub)", "\(PaymentCardType.JBC)", "Others"]

    let button = UIButton(type: .system)
    button.translatesAutoresizingMaskIntoConstraints = false

    button.heightAnchor.constraint(equalToConstant: 44).isActive = true
    button.widthAnchor.constraint(equalToConstant: 250).isActive = true
    
    button.setTitleColor(.lightGray, for: .normal)
    button.titleLabel?.font = .systemFont(ofSize: 18, weight: .light)
    
    button.setTitle(" Card Type", for: .normal)
    button.setTitleColor(.lightGray, for: .normal)
    button.contentHorizontalAlignment = .left
    button.backgroundColor = .black
    button.titleLabel?.font = .systemFont(ofSize: 18, weight: .light)
    
    if #available(iOS 14.0, *) {
        button.showsMenuAsPrimaryAction = true
        button.menu = UIMenu(children: customDiscounTypes.map({ item in
            UIAction(title: String(item)) { action in
                textField?.text = String(item)
                let a: String = textField!.text!
                button.setTitle("  \(a)", for: .normal)
                button.setTitleColor(.black, for: .normal)
                print(a)
                if a == "Others" {
                    (self.returnAlert?.textFields?[4] as? UITextField)?.isHidden = false
                    (self.returnAlert?.textFields?[4] as? UITextField)?.text = ""
                    (self.returnAlert?.textFields?[4] as? UITextField)?.placeholder = "Specify"
                } else if a != "Others"{
                    (self.returnAlert?.textFields?[4] as? UITextField)?.isHidden = true
                }

            }
        }))
    } else {
        // Fallback on earlier versions
    }
    textField?.leftView = button
    textField?.rightViewMode = .always
})

效果截图:
黑色区域为目标Button

可行方案

要让按钮宽度匹配TextField宽度,核心是移除固定宽度约束,通过Auto Layout绑定按钮与TextField的宽度,同时调整leftView的显示模式:

  1. 移除固定宽度约束:删除代码中button.widthAnchor.constraint(equalToConstant: 250).isActive = true这一行
  2. 绑定按钮与TextField的宽度约束:在将按钮设置为leftView后,添加按钮宽度等于TextField宽度的约束
  3. 设置leftView显示模式:显式设置textField?.leftViewMode = .always,确保leftView持续显示

修改后的完整代码

returnAlert?.addTextField(configurationHandler: { [self] (textField) in
    // Dropdown Start here
    let customDiscounTypes:[String] = ["\(PaymentCardType.MasterCard)", "\(PaymentCardType.VISA)", "\(PaymentCardType.AmericanExpress)", "\(PaymentCardType.DinnersClub)", "\(PaymentCardType.JBC)", "Others"]

    let button = UIButton(type: .system)
    button.translatesAutoresizingMaskIntoConstraints = false

    button.heightAnchor.constraint(equalToConstant: 44).isActive = true
    
    button.setTitleColor(.lightGray, for: .normal)
    button.titleLabel?.font = .systemFont(ofSize: 18, weight: .light)
    
    button.setTitle(" Card Type", for: .normal)
    button.setTitleColor(.lightGray, for: .normal)
    button.contentHorizontalAlignment = .left
    button.backgroundColor = .black
    button.titleLabel?.font = .systemFont(ofSize: 18, weight: .light)
    
    if #available(iOS 14.0, *) {
        button.showsMenuAsPrimaryAction = true
        button.menu = UIMenu(children: customDiscounTypes.map({ item in
            UIAction(title: String(item)) { action in
                textField?.text = String(item)
                let a: String = textField!.text!
                button.setTitle("  \(a)", for: .normal)
                button.setTitleColor(.black, for: .normal)
                print(a)
                if a == "Others" {
                    (self.returnAlert?.textFields?[4] as? UITextField)?.isHidden = false
                    (self.returnAlert?.textFields?[4] as? UITextField)?.text = ""
                    (self.returnAlert?.textFields?[4] as? UITextField)?.placeholder = "Specify"
                } else if a != "Others"{
                    (self.returnAlert?.textFields?[4] as? UITextField)?.isHidden = true
                }

            }
        }))
    } else {
        // Fallback on earlier versions
    }
    
    textField?.leftView = button
    textField?.leftViewMode = .always
    
    // 添加宽度匹配约束
    if let textField = textField {
        button.widthAnchor.constraint(equalTo: textField.widthAnchor).isActive = true
    }
})

补充说明

  • 如果按钮与TextField边缘存在间隙,可调整TextField的内边距,或给按钮添加负水平约束(如button.leadingAnchor.constraint(equalTo: textField.leadingAnchor, constant: -8).isActive = true)消除间隙
  • 若希望按钮高度也匹配TextField,可将按钮高度约束替换为button.heightAnchor.constraint(equalTo: textField.heightAnchor).isActive = true

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 20:57:06