首页 > 解决方案 > NightNight in Swift 改变主题,属性文本问题

问题描述

我目前正在尝试使用NightNight,这是一个易于使用的库,可以为应用程序添加明暗主题。如果您有兴趣在您的应用程序中添加两个主题,我建议您研究一下。

话虽如此,它就像一个魅力。它还没有得到完全支持,例如我缺少设置shadowImageaUITabBarController来更改“顶部边框”或分隔符的能力,但我想我可以稍后通过深入研究源代码来添加它。

我现在面临的一个问题是我无法更改attributedTexta的颜色UITextView。我肯定需要使用该attributedText属性,因为我想添加lineHeightMultiple. 我让一切正常工作,但是当我在主题之间切换时颜色不会改变。

是 a的UITextView一部分UICollectionViewCell,所以它被重用。每当我重新启动应用程序或开始在 中滚动时UICollectionView,文本都会更新(有时 - 由于重用,当单元格在屏幕上保持可见时它有时不会更新)。我觉得我需要更新或重新加载其他东西才能让这个库按我的需要工作。

目前我这样设置我的TextView:

let customTextViewStyle = NSMutableParagraphStyle()
customTextViewStyle.lineHeightMultiple = 1.2

let attributedString = NSMutableAttributedString(string: "This is the text that will be shown inside the TextView")

attributedString.setMixedAttributes([NNForegroundColorAttributeName: MixedColor(normal: lightCustomTextViewFontColor, night: darkCustomTextViewFontColor)], range: NSRange(location: 0, length: attributedString.length))
attributedString.addAttribute(NSAttributedString.Key.paragraphStyle, value: customTextViewStyle, range: NSRange(location: 0, length: attributedString.length))
attributedString.addAttribute(NSAttributedString.Key.font, value: UIFont.systemFont(ofSize: normalFontSize), range: NSRange(location: 0, length: attributedString.length))

customTextView.attributedText = attributedString

下面是NightNight源文件的片段,称为 NSMutableAttributedString,其中添加了一个观察者:

public extension NSMutableAttributedString {
    fileprivate struct AssociatedKeys {
        static var mixedAttrsKey = "mixedAttrs"
    }

    fileprivate var mixedAttrs: [String: [NSRange: MixedColor]] {
        get {
            if let dict = objc_getAssociatedObject(self, &AssociatedKeys.mixedAttrsKey) as? [String : [NSRange : MixedColor]] {
                return dict
            }
            self.mixedAttrs = [:]

            MixedColorAttributeNames.forEach { (mixed) in
                self.mixedAttrs[mixed] = [:]
            }

            return self.mixedAttrs
        }
        set {
            objc_setAssociatedObject(self, &AssociatedKeys.mixedAttrsKey, newValue as AnyObject, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)

            addNightObserver(#selector(_updateTitleAttributes))
        }
    }
}

然后 _updateTitleAttributes 看起来像这样:

@objc func _updateTitleAttributes() {

    MixedColorAttributeNamesDictionary.forEach { (mixed, normal) in
        if let foregroundColorDictionary = mixedAttrs[mixed] {
            foregroundColorDictionary.forEach({ (range, mixedColor) in
                self.addAttribute(normal, value: mixedColor.unfold(), range: range)
            })
        }

    }
}

我非常感谢这个问题的解决方案,因为我自己无法弄清楚。它是否与源有关 - 例如它没有正确更新?跟我有关系UICollectionViewCell吗?

提前致谢!

标签: iosswiftuicollectionviewthemesuicollectionviewcell

解决方案


推荐阅读