【问题标题】:UIButton subclass is changing font on clickUIButton 子类在单击时更改字体
【发布时间】:2022-01-02 09:27:41
【问题描述】:

我在故事板中内置的一系列按钮中看到了一些奇怪的行为。我有 4 个自定义类型的按钮 TakesContainerButton,当单击一个按钮时,它会更改为系统字体,但是当单击一个不同的按钮时,前一个按钮会返回到所需的字体,不确定这里发生了什么

按钮也嵌入在堆栈视图中,如果这很重要的话

这是按下其中一个按钮时的实现,其中buttons 是 4 个按钮的数组

@IBAction func filterPressed(_ sender: TakesContainerButton) {
        for button in buttons {
            button.unclick()
        }
        sender.click()
    }

这是自定义类

class TakesContainerButton: UIButton {

        
        var bottom = UIView()
        
        func click(){
            self.setTitleColor(.darkGray, for: .normal)
            let xOffset:CGFloat = 10
            bottom = UIView(frame: CGRect(x: xOffset / 2, y: self.frame.height - 3, width: self.frame.width - xOffset, height: 3))
            bottom.layer.cornerRadius = 1.5
            bottom.backgroundColor = .darkGray
            self.addSubview(bottom)
        }
        
        func unclick(){
            bottom.removeFromSuperview()
            self.setTitleColor(UIColor(hex: "8B8B8B"), for: .normal)
        }
        
        override func awakeFromNib(){
            setFont()
        }
        
        func setFont(){
            self.titleLabel?.font = UIFont(name: "Lato-Bold", size: 12)
        }
    }

【问题讨论】:

    标签: ios swift uibutton


    【解决方案1】:

    您是否有任何特定原因在每次点击时调用 setFont()。正如我所看到的,您没有更改字体,您应该在视图加载时设置此字体并保持原样。

    【讨论】:

    • 原来它只在 awakeFromNib 中,但我遇到了这个问题,所以我把它放在 click 和 unclick 中
    • 不需要每次都设置字体。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-25
    • 2016-09-07
    • 1970-01-01
    • 1970-01-01
    • 2014-04-05
    相关资源
    最近更新 更多