AskOverflow.Dev

AskOverflow.Dev Logo AskOverflow.Dev Logo

AskOverflow.Dev Navigation

  • 主页
  • 系统&网络
  • Ubuntu
  • Unix
  • DBA
  • Computer
  • Coding
  • LangChain

Mobile menu

Close
  • 主页
  • 系统&网络
    • 最新
    • 热门
    • 标签
  • Ubuntu
    • 最新
    • 热门
    • 标签
  • Unix
    • 最新
    • 标签
  • DBA
    • 最新
    • 标签
  • Computer
    • 最新
    • 标签
  • Coding
    • 最新
    • 标签
主页 / coding / 问题 / 79595632
Accepted
Alex Urrutia
Alex Urrutia
Asked: 2025-04-28 09:06:46 +0800 CST2025-04-28 09:06:46 +0800 CST 2025-04-28 09:06:46 +0800 CST

我的自定义 UIview 类中的主视图边框位于另一个视图之上

  • 772

我的问题的屏幕截图

我遇到了一个问题:我自定义的 UIview 类的主视图边框覆盖了该类中的 rankbadgeview。我怎么也想不出原因。我试过把 rankbadgeview 子视图连同其中的 uilabel 一起放到最上面,但仍然不行。谁能帮我看看这个问题?

class LeaderboardCircleView: UIView {
    private let mainLabel = UILabel()
    let rankBadgeView = UIView()
    private let rankLabel = UILabel()
    private let scoreLabel = UILabel()
    
    init(mainText: String, rankText: String, backgroundColor: UIColor, score: Int) {
        super.init(frame: .zero)
        setupViews()
        configure(mainText: mainText, rankText: rankText, backgroundColor: backgroundColor, score: score)
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }


    private func updateScoreLabelWith(score: Int) {
        let trophyAttachment = NSTextAttachment()
        trophyAttachment.image = UIImage(systemName: "trophy.fill")?.withTintColor(.systemYellow, renderingMode: .alwaysOriginal)
        trophyAttachment.bounds = CGRect(x: 0, y: -2, width: 16, height: 16)
        
        let trophyString = NSAttributedString(attachment: trophyAttachment)
        let scoreString = NSAttributedString(string: " \(score) pts", attributes: [
            .font: AppStyle.shared.headerFont(size: 12),
            .foregroundColor: UIColor.darkGray
        ])
        
        let fullScoreText = NSMutableAttributedString()
        fullScoreText.append(trophyString)
        fullScoreText.append(scoreString)
        
        scoreLabel.attributedText = fullScoreText
    }

    
    private func setupViews() {
        layer.borderWidth = 2
        layer.borderColor = AppStyle.shared.primaryColor?.cgColor
        translatesAutoresizingMaskIntoConstraints = false
        clipsToBounds = false
        
        mainLabel.translatesAutoresizingMaskIntoConstraints = false
        mainLabel.textAlignment = .center
        mainLabel.adjustsFontSizeToFitWidth = true
        mainLabel.minimumScaleFactor = 0.5
        mainLabel.numberOfLines = 2
        mainLabel.font = AppStyle.shared.headerFont(size: 18)
        mainLabel.textColor = .white
        addSubview(mainLabel)
        
        rankBadgeView.translatesAutoresizingMaskIntoConstraints = false
        rankBadgeView.clipsToBounds = true
        rankBadgeView.backgroundColor = AppStyle.shared.primaryColor
        rankBadgeView.layer.zPosition = 1  // Sends it behind the border

        addSubview(rankBadgeView)
        
        rankLabel.translatesAutoresizingMaskIntoConstraints = false
        rankLabel.textAlignment = .center
        rankLabel.font = AppStyle.shared.headerFont(size: 12)
        rankLabel.textColor = .white
        rankBadgeView.addSubview(rankLabel)
        
        scoreLabel.translatesAutoresizingMaskIntoConstraints = false
        scoreLabel.textAlignment = .center
        scoreLabel.adjustsFontSizeToFitWidth = true
        scoreLabel.minimumScaleFactor = 0.5
        scoreLabel.numberOfLines = 1
        addSubview(scoreLabel)
        
        NSLayoutConstraint.activate([
            mainLabel.leadingAnchor.constraint(equalTo: leadingAnchor, constant: 10),
            mainLabel.trailingAnchor.constraint(equalTo: trailingAnchor, constant: -10),
            mainLabel.centerXAnchor.constraint(equalTo: centerXAnchor),
            mainLabel.centerYAnchor.constraint(equalTo: centerYAnchor),
            
            rankBadgeView.centerXAnchor.constraint(equalTo: centerXAnchor),
            rankBadgeView.bottomAnchor.constraint(equalTo: bottomAnchor, constant: 12),
            rankBadgeView.widthAnchor.constraint(equalToConstant: 30),
            rankBadgeView.heightAnchor.constraint(equalToConstant: 30),
            
            rankLabel.centerXAnchor.constraint(equalTo: rankBadgeView.centerXAnchor),
            rankLabel.centerYAnchor.constraint(equalTo: rankBadgeView.centerYAnchor),
            
            scoreLabel.topAnchor.constraint(equalTo: rankBadgeView.bottomAnchor, constant: 4),
            scoreLabel.centerXAnchor.constraint(equalTo: centerXAnchor)
        ])
        
        bringSubviewToFront(rankBadgeView)
        rankBadgeView.bringSubviewToFront(scoreLabel)
    }
    
    private func configure(mainText: String, rankText: String, backgroundColor: UIColor, score: Int) {
        mainLabel.text = mainText
        self.backgroundColor = backgroundColor
        rankLabel.text = rankText
        
        let trophyAttachment = NSTextAttachment()
        trophyAttachment.image = UIImage(systemName: "trophy.fill")?.withTintColor(.systemYellow, renderingMode: .alwaysOriginal)
        trophyAttachment.bounds = CGRect(x: 0, y: -2, width: 16, height: 16)
        
        let trophyString = NSAttributedString(attachment: trophyAttachment)
        let scoreString = NSAttributedString(string: " \(score) pts", attributes: [
            .font: AppStyle.shared.headerFont(size: 12),
            .foregroundColor: UIColor.darkGray
        ])
        
        let fullScoreText = NSMutableAttributedString()
        fullScoreText.append(trophyString)
        fullScoreText.append(scoreString)
        
        scoreLabel.attributedText = fullScoreText
    }
    
    override func layoutSubviews() {
        super.layoutSubviews()
        
        layer.cornerRadius = bounds.width / 2
        rankBadgeView.layer.cornerRadius = rankBadgeView.bounds.width / 2
        
        layer.shadowColor = UIColor.black.cgColor
        layer.shadowOpacity = 0.2
        layer.shadowRadius = 6.0
        layer.shadowOffset = CGSize(width: 0, height: 4)
        layer.masksToBounds = false
        
        rankBadgeView.layer.shadowColor = UIColor.black.cgColor
        rankBadgeView.layer.shadowOpacity = 0.2
        rankBadgeView.layer.shadowRadius = 4.0
        rankBadgeView.layer.shadowOffset = CGSize(width: 0, height: 2)
        rankBadgeView.layer.masksToBounds = false
    }
    
    func update(mainText: String, rankText: String, backgroundColor: UIColor, score: Int) {
        configure(mainText: mainText, rankText: rankText, backgroundColor: backgroundColor, score: score)
    }
}
  • 2 2 个回答
  • 53 Views

2 个回答

  • Voted
  1. Best Answer
    DonMag
    2025-04-28T22:02:06+08:002025-04-28T22:02:06+08:00

    来自 Apple 的文档:“边框......合成在接收器的内容和子层之上......”

    layer.border因此,如果我们向视图添加子视图,并像这样设置视图的属性:

    class ViewController: UIViewController {
        
        override func viewDidLoad() {
            super.viewDidLoad()
            view.backgroundColor = .systemBackground
    
            let mainView = UIView(frame: .init(x: 40, y: 100, width: 120, height: 100))
            let subView = UIView(frame: .init(x: 60, y: 60, width: 100, height: 60))
            
            mainView.backgroundColor = .systemBlue
            subView.backgroundColor = .systemYellow
            
            view.addSubview(mainView)
            mainView.addSubview(subView)
            
            mainView.layer.borderColor = UIColor.red.cgColor
            mainView.layer.borderWidth = 4
            
        }
    }
    

    我们得到这个结果:

    错误的

    相反,正如matt评论所说,我们想要绘制(使用CAShapeLayer)带边框的形状:

    class ViewController: UIViewController {
        
        override func viewDidLoad() {
            super.viewDidLoad()
            view.backgroundColor = .systemBackground
    
            let mainView = UIView(frame: .init(x: 40, y: 100, width: 120, height: 100))
            let subView = UIView(frame: .init(x: 60, y: 60, width: 100, height: 60))
            
            mainView.backgroundColor = .systemBlue
            subView.backgroundColor = .systemYellow
    
            let shapeLayer = CAShapeLayer()
            shapeLayer.lineWidth = 4
            shapeLayer.strokeColor = UIColor.red.cgColor
            shapeLayer.fillColor = UIColor.systemBlue.cgColor
            
            let path = UIBezierPath(rect: .init(x: 0, y: 0, width: 120, height: 100))
            shapeLayer.path = path.cgPath
            mainView.layer.addSublayer(shapeLayer)
            
            view.addSubview(mainView)
            mainView.addSubview(subView)
            
        }
    }
    

    我们得到了这个:

    固定的


    这是经过修改的课程CAShapeLayer- 查找以以下内容开头的相关评论// DonMag -:

    class AppStyle: NSObject {
        static let shared = AppStyle()
        
        let primaryColor = UIColor(red: 0.260, green: 0.346, blue: 0.579, alpha: 1.0)
        
        func headerFont(size: CGFloat) -> UIFont {
            return UIFont.systemFont(ofSize: size, weight: .bold)
        }
    }
    
    class LeaderboardCircleView: UIView {
        private let mainLabel = UILabel()
        let rankBadgeView = UIView()
        private let rankLabel = UILabel()
        private let scoreLabel = UILabel()
        
        // DonMag - this shape layer will draw the main bordered-circle
        private let mainCircleLayer: CAShapeLayer = CAShapeLayer()
        
        init(mainText: String, rankText: String, backgroundColor: UIColor, score: Int) {
            super.init(frame: .zero)
            setupViews()
            configure(mainText: mainText, rankText: rankText, backgroundColor: backgroundColor, score: score)
        }
        
        required init?(coder: NSCoder) {
            fatalError("init(coder:) has not been implemented")
        }
        
        
        private func updateScoreLabelWith(score: Int) {
            let trophyAttachment = NSTextAttachment()
            trophyAttachment.image = UIImage(systemName: "trophy.fill")?.withTintColor(.systemYellow, renderingMode: .alwaysOriginal)
            trophyAttachment.bounds = CGRect(x: 0, y: -2, width: 16, height: 16)
            
            let trophyString = NSAttributedString(attachment: trophyAttachment)
            let scoreString = NSAttributedString(string: " \(score) pts", attributes: [
                .font: AppStyle.shared.headerFont(size: 12),
                .foregroundColor: UIColor.darkGray
            ])
            
            let fullScoreText = NSMutableAttributedString()
            fullScoreText.append(trophyString)
            fullScoreText.append(scoreString)
            
            scoreLabel.attributedText = fullScoreText
        }
        
        
        private func setupViews() {
            // DonMag - don't set self's layer border properties
            //layer.borderWidth = 2
            //layer.borderColor = UIColor.red.cgColor // AppStyle.shared.primaryColor?.cgColor
            
            // DonMag - main circle properties
            mainCircleLayer.lineWidth = 4
            mainCircleLayer.strokeColor = AppStyle.shared.primaryColor.cgColor
            
            // DonMag - add circle shape layer
            layer.addSublayer(mainCircleLayer)
            
            translatesAutoresizingMaskIntoConstraints = false
            clipsToBounds = false
            
            mainLabel.translatesAutoresizingMaskIntoConstraints = false
            mainLabel.textAlignment = .center
            mainLabel.adjustsFontSizeToFitWidth = true
            mainLabel.minimumScaleFactor = 0.5
            mainLabel.numberOfLines = 2
            mainLabel.font = AppStyle.shared.headerFont(size: 18)
            mainLabel.textColor = .white
            addSubview(mainLabel)
            
            rankBadgeView.translatesAutoresizingMaskIntoConstraints = false
            rankBadgeView.clipsToBounds = true
            rankBadgeView.backgroundColor = AppStyle.shared.primaryColor
            
            // DonMag - not needed
            //rankBadgeView.layer.zPosition = 1  // Sends it behind the border
            
            addSubview(rankBadgeView)
            
            rankLabel.translatesAutoresizingMaskIntoConstraints = false
            rankLabel.textAlignment = .center
            rankLabel.font = AppStyle.shared.headerFont(size: 12)
            rankLabel.textColor = .white
            rankBadgeView.addSubview(rankLabel)
            
            scoreLabel.translatesAutoresizingMaskIntoConstraints = false
            scoreLabel.textAlignment = .center
            scoreLabel.adjustsFontSizeToFitWidth = true
            scoreLabel.minimumScaleFactor = 0.5
            scoreLabel.numberOfLines = 1
            addSubview(scoreLabel)
            
            NSLayoutConstraint.activate([
                mainLabel.leadingAnchor.constraint(equalTo: leadingAnchor, constant: 10),
                mainLabel.trailingAnchor.constraint(equalTo: trailingAnchor, constant: -10),
                mainLabel.centerXAnchor.constraint(equalTo: centerXAnchor),
                mainLabel.centerYAnchor.constraint(equalTo: centerYAnchor),
                
                rankBadgeView.centerXAnchor.constraint(equalTo: centerXAnchor),
                rankBadgeView.bottomAnchor.constraint(equalTo: bottomAnchor, constant: 12),
                rankBadgeView.widthAnchor.constraint(equalToConstant: 30),
                rankBadgeView.heightAnchor.constraint(equalToConstant: 30),
                
                rankLabel.centerXAnchor.constraint(equalTo: rankBadgeView.centerXAnchor),
                rankLabel.centerYAnchor.constraint(equalTo: rankBadgeView.centerYAnchor),
                
                scoreLabel.topAnchor.constraint(equalTo: rankBadgeView.bottomAnchor, constant: 4),
                scoreLabel.centerXAnchor.constraint(equalTo: centerXAnchor)
            ])
            
            // DonMag - not needed
            //bringSubviewToFront(rankBadgeView)
            //rankBadgeView.bringSubviewToFront(scoreLabel)
        }
        
        private func configure(mainText: String, rankText: String, backgroundColor: UIColor, score: Int) {
            mainLabel.text = mainText
            
            // DonMag - set self background to clear
            self.backgroundColor = .clear
            
            // DonMag - main circle layer fill color
            mainCircleLayer.fillColor = backgroundColor.cgColor
            
            rankLabel.text = rankText
            
            let trophyAttachment = NSTextAttachment()
            trophyAttachment.image = UIImage(systemName: "trophy.fill")?.withTintColor(.systemYellow, renderingMode: .alwaysOriginal)
            trophyAttachment.bounds = CGRect(x: 0, y: -2, width: 16, height: 16)
            
            let trophyString = NSAttributedString(attachment: trophyAttachment)
            let scoreString = NSAttributedString(string: " \(score) pts", attributes: [
                .font: AppStyle.shared.headerFont(size: 12),
                .foregroundColor: UIColor.darkGray
            ])
            
            let fullScoreText = NSMutableAttributedString()
            fullScoreText.append(trophyString)
            fullScoreText.append(scoreString)
            
            scoreLabel.attributedText = fullScoreText
        }
        
        override func layoutSubviews() {
            super.layoutSubviews()
            
            // DonMag - don't set self's corner radius
            //layer.cornerRadius = bounds.width / 2
    
            // DonMag - oval (circle) path for main circle
            mainCircleLayer.path = UIBezierPath(ovalIn: bounds).cgPath
            
            rankBadgeView.layer.cornerRadius = rankBadgeView.bounds.width / 2
            
            layer.shadowColor = UIColor.black.cgColor
            layer.shadowOpacity = 0.2
            layer.shadowRadius = 6.0
            layer.shadowOffset = CGSize(width: 0, height: 4)
            layer.masksToBounds = false
            
            rankBadgeView.layer.shadowColor = UIColor.black.cgColor
            rankBadgeView.layer.shadowOpacity = 0.2
            rankBadgeView.layer.shadowRadius = 4.0
            rankBadgeView.layer.shadowOffset = CGSize(width: 0, height: 2)
            rankBadgeView.layer.masksToBounds = false
        }
        
        func update(mainText: String, rankText: String, backgroundColor: UIColor, score: Int) {
            configure(mainText: mainText, rankText: rankText, backgroundColor: backgroundColor, score: score)
        }
    }
    

    现在我们得到了想要的结果,没有重叠的边框:

    最终的

    • 0
  2. Lekha Mishra
    2025-04-28T21:14:36+08:002025-04-28T21:14:36+08:00

    问题不在于视图的 z-index 排序。

    rankBadgeView.bottomAnchor.constraint(equalTo: bottomAnchor, constant: 12)
    这条线位于主视图底部下方rankBadgeView 12 个点的LeaderboardCircleView位置 ( )。由于徽章严格来说位于边界之外,因此无论 z 位置或 如何,边框都会绘制在其上方bringSubviewToFront()。

    即使您设置:

    clipsToBounds = false 
    

    图层的边框渲染不符合您预期,无法尊重子视图 zPosition 的边界外属性。在 Core Animation 中,除非您将边框移入子视图或将其遮罩,否则边框会绘制在所有内容之上。

    您可以在边界rankBadgeView 内移动

    不要将徽章放在主视图下方12 点的位置:

    rankBadgeView.bottomAnchor.constraint(equalTo: bottomAnchor, constant: -6) 
    

    这样可以让徽章保持在边界内。结合适当的 z 位置,徽章将显示在边界上方。如果有效,请告诉我。

    • -2

相关问题

  • 将复制活动的序列号添加到 Blob

  • Packer 动态源重复工件

  • 选择每组连续 1 的行

  • 图形 API 调用列表 subscribedSkus 状态权限不足,但已授予权限

  • 根据列值创建单独的 DF 的函数

Sidebar

Stats

  • 问题 205573
  • 回答 270741
  • 最佳答案 135370
  • 用户 68524
  • 热门
  • 回答
  • Marko Smith

    重新格式化数字,在固定位置插入分隔符

    • 6 个回答
  • Marko Smith

    为什么 C++20 概念会导致循环约束错误,而老式的 SFINAE 不会?

    • 2 个回答
  • Marko Smith

    VScode 自动卸载扩展的问题(Material 主题)

    • 2 个回答
  • Marko Smith

    Vue 3:创建时出错“预期标识符但发现‘导入’”[重复]

    • 1 个回答
  • Marko Smith

    具有指定基础类型但没有枚举器的“枚举类”的用途是什么?

    • 1 个回答
  • Marko Smith

    如何修复未手动导入的模块的 MODULE_NOT_FOUND 错误?

    • 6 个回答
  • Marko Smith

    `(表达式,左值) = 右值` 在 C 或 C++ 中是有效的赋值吗?为什么有些编译器会接受/拒绝它?

    • 3 个回答
  • Marko Smith

    在 C++ 中,一个不执行任何操作的空程序需要 204KB 的堆,但在 C 中则不需要

    • 1 个回答
  • Marko Smith

    PowerBI 目前与 BigQuery 不兼容:Simba 驱动程序与 Windows 更新有关

    • 2 个回答
  • Marko Smith

    AdMob:MobileAds.initialize() - 对于某些设备,“java.lang.Integer 无法转换为 java.lang.String”

    • 1 个回答
  • Martin Hope
    Fantastic Mr Fox msvc std::vector 实现中仅不接受可复制类型 2025-04-23 06:40:49 +0800 CST
  • Martin Hope
    Howard Hinnant 使用 chrono 查找下一个工作日 2025-04-21 08:30:25 +0800 CST
  • Martin Hope
    Fedor 构造函数的成员初始化程序可以包含另一个成员的初始化吗? 2025-04-15 01:01:44 +0800 CST
  • Martin Hope
    Petr Filipský 为什么 C++20 概念会导致循环约束错误,而老式的 SFINAE 不会? 2025-03-23 21:39:40 +0800 CST
  • Martin Hope
    Catskul C++20 是否进行了更改,允许从已知绑定数组“type(&)[N]”转换为未知绑定数组“type(&)[]”? 2025-03-04 06:57:53 +0800 CST
  • Martin Hope
    Stefan Pochmann 为什么 {2,3,10} 和 {x,3,10} (x=2) 的顺序不同? 2025-01-13 23:24:07 +0800 CST
  • Martin Hope
    Chad Feller 在 5.2 版中,bash 条件语句中的 [[ .. ]] 中的分号现在是可选的吗? 2024-10-21 05:50:33 +0800 CST
  • Martin Hope
    Wrench 为什么双破折号 (--) 会导致此 MariaDB 子句评估为 true? 2024-05-05 13:37:20 +0800 CST
  • Martin Hope
    Waket Zheng 为什么 `dict(id=1, **{'id': 2})` 有时会引发 `KeyError: 'id'` 而不是 TypeError? 2024-05-04 14:19:19 +0800 CST
  • Martin Hope
    user924 AdMob:MobileAds.initialize() - 对于某些设备,“java.lang.Integer 无法转换为 java.lang.String” 2024-03-20 03:12:31 +0800 CST

热门标签

python javascript c++ c# java typescript sql reactjs html

Explore

  • 主页
  • 问题
    • 最新
    • 热门
  • 标签
  • 帮助

Footer

AskOverflow.Dev

关于我们

  • 关于我们
  • 联系我们

Legal Stuff

  • Privacy Policy

Language

  • Pt
  • Server
  • Unix

© 2023 AskOverflow.DEV All Rights Reserve