【问题标题】:iOS custom view,change UILabel textColor/isHidden not workingiOS 自定义视图,更改 UILabel textColor/isHidden 不起作用
【发布时间】:2025-12-18 12:35:02
【问题描述】:

Swift 4.2/iOS 12/Xcode 10。 我做了一个自定义视图,里面有一个UILabel(名称StepView.xib & StepView.swift),xib文件中的UILabel通过IBOutlet连接到swift文件。然后,我在viewController中使用StepView。当我想在viewController中更改UILabel textColor,它不起作用,我想知道原因。

class StepView: UIView {

    @IBOutlet var labels: [UILabel]!

    ...

    private func setSelected(current phase: ClosedRange<Int>,
                             select srange: ClosedRange<Int>){
        for p in phase {
            labels[p].textColor = R.color.mainTextColor()
        }
    }

    // MARK: - Init
    required init?(coder aDecoder: NSCoder) {
       super.init(coder: aDecoder)
       initSubviews()
    }

    override init(frame: CGRect) {
        super.init(frame: frame)
        initSubviews()
    }

    func initSubviews() {

       let nib = UINib(nibName: "StepView", bundle: Bundle(for: type(of: self)))
       nib.instantiate(withOwner: self, options: nil)
       contentView.frame = bounds
       addSubview(contentView)
    }
}

更多信息: 我已经在XIB中设置了UILabel的颜色,然后我在代码中更改了UILabel的颜色,它是无效的。我将 UILabel 颜色重置为默认值,然后在代码中更改 UILabel 的颜色,它的工作。我想知道原因。

【问题讨论】:

  • 您要调用的代码在哪里,以便将 textColorUIViewController 更改为 UIViewController
  • 我只是在 viewController 的 viewDidLoad 中调用 setSelected(current: 1...3,select: 4...5)。
  • 在您的 setSelect 方法中,您正在更改所选标签的颜色,但不会重置未选择标签的颜色。
  • 同样的问题:*.com/questions/25355709/…

标签: ios swift


【解决方案1】:

设置和重置选定标签和未选定标签的文本颜色。

 private func setSelected(current phase: ClosedRange<Int>,
                             select srange: ClosedRange<Int>){
        for p in phase {
            labels[p].textColor = R.color.mainTextColor()
        }
        for s in srange {
            labels[s].textColor = R.color.unSelectedColor()
        }
    }

【讨论】: