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

iOS开发:移除UIView的maskedCorners遮罩圆角无效怎么办?

解决可展开UITableViewCell中topContainer圆角遮罩不恢复的问题

问题原因

maskedCorners的空数组[]表示不应用任何圆角遮罩,但你之前已经设置了cornerRadius = 12,这时候空数组会导致所有圆角都不显示,而非恢复四个角的圆角。正确做法是将maskedCorners设置为包含所有四个圆角的集合,让之前设置的cornerRadius作用于全部四个角。

解决方案

  1. 恢复全部圆角遮罩:cell收起时,将maskedCorners设为包含四个角的枚举值集合,iOS 11及以上可直接用.allCorners简化代码。
  2. 确保masksToBounds开启:初始化topContainer时设置topContainer.layer.masksToBounds = true,否则圆角不会生效。
  3. 优化动画布局:在动画块内添加layoutIfNeeded(),确保约束更新后的布局立即生效,避免卡顿或布局异常。

修改后的代码

// 建议在topContainer初始化阶段添加以下配置
topContainer.layer.cornerRadius = 12
topContainer.layer.masksToBounds = true

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    if let cell = tableView.cellForRow(at: indexPath) as? ExpandableProgramCell {
        cell.setExpanded(false)
        tableView.performBatchUpdates(nil)
    }
}

func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {
    if let cell = tableView.cellForRow(at: indexPath) as? ExpandableProgramCell {
        cell.setExpanded(true)
        tableView.performBatchUpdates(nil)
    }
}

func setExpanded(_ expanded: Bool) {
    if !expanded {
        // 展开时仅保留左上、右上圆角
        topContainer.layer.maskedCorners = [.layerMaxXMinYCorner, .layerMinXMinYCorner]
        UIView.animate(withDuration: 0.3, delay: 0.0, options: .curveEaseInOut, animations: {
            let upsideDown = CGAffineTransform(rotationAngle: .pi * -0.999)
            self.arrowImageView.transform = upsideDown
            self.bottomContainer.snp.remakeConstraints { make in
                make.top.equalTo(self.topContainer.snp.bottom)
                make.left.right.bottom.equalToSuperview()
            }
            self.layoutIfNeeded()
        })
    } else {
        // 收起时恢复全部四个圆角
        topContainer.layer.maskedCorners = .allCorners
        UIView.animate(withDuration: 0.3, delay: 0.0, options: .curveEaseInOut, animations: {
            self.arrowImageView.transform = .identity
            self.bottomContainer.snp.remakeConstraints { make in
                make.top.equalTo(self.topContainer.snp.bottom)
                make.left.right.equalToSuperview()
            }
            self.layoutIfNeeded()
        })
    }
}

额外说明

  • 若需兼容iOS 11以下版本,将.allCorners替换为完整枚举集合:[.layerMinXMinYCorner, .layerMaxXMinYCorner, .layerMinXMaxYCorner, .layerMaxXMaxYCorner]即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 12:54:59