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

Swift分段控制UITableView中Anchor类型缺失的替代方案求助

问题解决:Anchor类型找不到的替代方案

你遇到的Anchor类型并非UIKit原生类型,而是3年前视频里自定义的约束容器类型。只需自行定义对应的结构体,并修正函数返回逻辑即可解决,具体步骤如下:

1. 定义约束容器结构体

补上代码中已使用但未定义的AnchoredConstraints结构体,用来存储创建的布局约束:

struct AnchoredConstraints {
    var top: NSLayoutConstraint?
    var leading: NSLayoutConstraint?
    var bottom: NSLayoutConstraint?
    var trailing: NSLayoutConstraint?
    var width: NSLayoutConstraint?
    var height: NSLayoutConstraint?
}

2. 修正anchor函数的返回值与逻辑

将原函数返回值从Anchor改为AnchoredConstraints,同时补全约束激活和返回容器的代码(原代码遗漏了约束激活逻辑与返回值):

extension UIView {
    func anchor(top: NSLayoutYAxisAnchor?, leading: NSLayoutXAxisAnchor?,
                bottom: NSLayoutYAxisAnchor?, trailing: NSLayoutXAxisAnchor?, 
                padding: UIEdgeInsets = .zero, size: CGSize = .zero) -> AnchoredConstraints {
        translatesAutoresizingMaskIntoConstraints = false
    
        var anchoredConstraints = AnchoredConstraints()
    
        if let top = top {
            anchoredConstraints.top = topAnchor.constraint(equalTo: top, constant: padding.top)
            anchoredConstraints.top?.isActive = true
        }
    
        if let leading = leading {
            anchoredConstraints.leading = leadingAnchor.constraint(equalTo: leading, constant: padding.left)
            anchoredConstraints.leading?.isActive = true
        }
    
        if let bottom = bottom {
            anchoredConstraints.bottom = bottomAnchor.constraint(equalTo: bottom, constant: -padding.bottom)
            anchoredConstraints.bottom?.isActive = true
        }
    
        if let trailing = trailing {
            anchoredConstraints.trailing = trailingAnchor.constraint(equalTo: trailing, constant: -padding.right)
            anchoredConstraints.trailing?.isActive = true
        }
    
        if size.width != 0 {
            anchoredConstraints.width = widthAnchor.constraint(equalToConstant: size.width)
            anchoredConstraints.width?.isActive = true
        }
        if size.height != 0 {
            anchoredConstraints.height = heightAnchor.constraint(equalToConstant: size.height)
            anchoredConstraints.height?.isActive = true
        }
        
        return anchoredConstraints
    }
}

补充说明

  • 原代码遗漏了trailing约束的处理逻辑,上述代码已补全
  • 所有布局约束必须设置isActive = true才会生效,原代码仅激活了宽高约束,现在统一补全
  • 返回的AnchoredConstraints容器可让你后续方便修改或停用特定约束

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 07:55:19