AskOverflow.Dev

AskOverflow.Dev Logo AskOverflow.Dev Logo

AskOverflow.Dev Navigation

  • Início
  • system&network
  • Ubuntu
  • Unix
  • DBA
  • Computer
  • Coding
  • LangChain

Mobile menu

Close
  • Início
  • system&network
    • Recentes
    • Highest score
    • tags
  • Ubuntu
    • Recentes
    • Highest score
    • tags
  • Unix
    • Recentes
    • tags
  • DBA
    • Recentes
    • tags
  • Computer
    • Recentes
    • tags
  • Coding
    • Recentes
    • tags
Início / coding / Perguntas / 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

A borda da visualização principal na minha classe UIview personalizada está em cima de outra visualização

  • 772

Captura de tela do meu problema

Estou com um problema em que a borda da visualização principal de uma classe UIview personalizada está sobrepondo a rankbadgeview dentro dessa classe personalizada. Não consigo entender o porquê. Tentei trazer a subvisualização rankbadgeview para a frente, junto com o uilabel dentro dela, mas ainda não funciona. Alguém pode me ajudar a identificar o problema?

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 respostas
  • 53 Views

2 respostas

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

    Dos documentos da Apple : "A borda... é composta acima do conteúdo e das subcamadas do receptor..."

    Então, se adicionarmos uma subvisualização a uma visualização e definirmos as layer.borderpropriedades da visualização assim:

    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
            
        }
    }
    

    obtemos este resultado:

    errado

    Em vez disso, conforme mattcomentado, queremos desenhar (usando um CAShapeLayer) a forma com borda:

    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)
            
        }
    }
    

    e temos isso:

    fixo


    Aqui está sua classe com CAShapeLayermodificação - procure por comentários relacionados começando com // 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)
        }
    }
    

    e agora obtemos o resultado desejado, sem a borda sobreposta:

    final

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

    O problema não é a ordenação z-index das visualizações.

    rankBadgeView.bottomAnchor.constraint(equalTo: bottomAnchor, constant: 12)
    Esta linha posiciona-se rankBadgeView 12 pontos abaixo da parte inferior da vista principal ( LeaderboardCircleView). Como o emblema está tecnicamente fora dos limites , a borda é desenhada sobre ele , independentemente da posição z ou bringSubviewToFront().

    Mesmo que você defina:

    clipsToBounds = false 
    

    A renderização das bordas da camada não respeita o zPosition da subvisualização fora dos limites da maneira esperada. As bordas são desenhadas sobre tudo no Core Animation, a menos que você as mova para as subvisualizações ou as mascare.

    Você pode mover o rankBadgeView interior dos limites

    Em vez de colocar o emblema 12 pontos abaixo da vista principal:

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

    Isso mantém o emblema dentro dos limites. Combinado com o posicionamento z correto, o emblema será exibido acima da borda. Me avise se funcionar.

    • -2

relate perguntas

  • Adicionar número de série para atividade de cópia ao blob

  • A fonte dinâmica do empacotador duplica artefatos

  • Selecione linhas por grupo com 1s consecutivos

  • Lista de chamada de API de gráfico subscritoSkus estados Privilégios insuficientes enquanto os privilégios são concedidos

  • Função para criar DFs separados com base no valor da coluna

Sidebar

Stats

  • Perguntas 205573
  • respostas 270741
  • best respostas 135370
  • utilizador 68524
  • Highest score
  • respostas
  • Marko Smith

    Reformatar números, inserindo separadores em posições fixas

    • 6 respostas
  • Marko Smith

    Por que os conceitos do C++20 causam erros de restrição cíclica, enquanto o SFINAE antigo não?

    • 2 respostas
  • Marko Smith

    Problema com extensão desinstalada automaticamente do VScode (tema Material)

    • 2 respostas
  • Marko Smith

    Vue 3: Erro na criação "Identificador esperado, mas encontrado 'import'" [duplicado]

    • 1 respostas
  • Marko Smith

    Qual é o propósito de `enum class` com um tipo subjacente especificado, mas sem enumeradores?

    • 1 respostas
  • Marko Smith

    Como faço para corrigir um erro MODULE_NOT_FOUND para um módulo que não importei manualmente?

    • 6 respostas
  • Marko Smith

    `(expression, lvalue) = rvalue` é uma atribuição válida em C ou C++? Por que alguns compiladores aceitam/rejeitam isso?

    • 3 respostas
  • Marko Smith

    Um programa vazio que não faz nada em C++ precisa de um heap de 204 KB, mas não em C

    • 1 respostas
  • Marko Smith

    PowerBI atualmente quebrado com BigQuery: problema de driver Simba com atualização do Windows

    • 2 respostas
  • Marko Smith

    AdMob: MobileAds.initialize() - "java.lang.Integer não pode ser convertido em java.lang.String" para alguns dispositivos

    • 1 respostas
  • Martin Hope
    Fantastic Mr Fox Somente o tipo copiável não é aceito na implementação std::vector do MSVC 2025-04-23 06:40:49 +0800 CST
  • Martin Hope
    Howard Hinnant Encontre o próximo dia da semana usando o cronógrafo 2025-04-21 08:30:25 +0800 CST
  • Martin Hope
    Fedor O inicializador de membro do construtor pode incluir a inicialização de outro membro? 2025-04-15 01:01:44 +0800 CST
  • Martin Hope
    Petr Filipský Por que os conceitos do C++20 causam erros de restrição cíclica, enquanto o SFINAE antigo não? 2025-03-23 21:39:40 +0800 CST
  • Martin Hope
    Catskul O C++20 mudou para permitir a conversão de `type(&)[N]` de matriz de limites conhecidos para `type(&)[]` de matriz de limites desconhecidos? 2025-03-04 06:57:53 +0800 CST
  • Martin Hope
    Stefan Pochmann Como/por que {2,3,10} e {x,3,10} com x=2 são ordenados de forma diferente? 2025-01-13 23:24:07 +0800 CST
  • Martin Hope
    Chad Feller O ponto e vírgula agora é opcional em condicionais bash com [[ .. ]] na versão 5.2? 2024-10-21 05:50:33 +0800 CST
  • Martin Hope
    Wrench Por que um traço duplo (--) faz com que esta cláusula MariaDB seja avaliada como verdadeira? 2024-05-05 13:37:20 +0800 CST
  • Martin Hope
    Waket Zheng Por que `dict(id=1, **{'id': 2})` às vezes gera `KeyError: 'id'` em vez de um TypeError? 2024-05-04 14:19:19 +0800 CST
  • Martin Hope
    user924 AdMob: MobileAds.initialize() - "java.lang.Integer não pode ser convertido em java.lang.String" para alguns dispositivos 2024-03-20 03:12:31 +0800 CST

Hot tag

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

Explore

  • Início
  • Perguntas
    • Recentes
    • Highest score
  • tag
  • help

Footer

AskOverflow.Dev

About Us

  • About Us
  • Contact Us

Legal Stuff

  • Privacy Policy

Language

  • Pt
  • Server
  • Unix

© 2023 AskOverflow.DEV All Rights Reserve