Set text attributes via UIAppearance in a custom subclass of UIView in Swift

Alignment with NSHipster , "the presence of user classes in the user interface that corresponds to UIAppearance is not only the best practice, but also demonstrates a certain level of assistance in its implementation."

Therefore, I am trying to set the text attributes, which are later used to create NSAttributedString, for a property var titleTextAttributes: [String : AnyObject]?in a subclass UIView, for example:

func applyAppearance() {

    UINavigationBar.appearance().translucent = true
    UINavigationBar.appearance().tintColor = UIColor(named: .NavBarTextColor)
    UINavigationBar.appearance().barTintColor = UIColor(named: .NavBarBlue)
    UINavigationBar.appearance().titleTextAttributes = [
        NSForegroundColorAttributeName: UIColor(named: .NavBarTextColor),
        NSFontAttributeName: UIFont.navBarTitleFont()!
    ]

    ActionBarView.appearance().backgroundColor = UIColor(white: 1, alpha: 0.15)
    ActionBarView.appearance().titleTextAttributes = [
        NSKernAttributeName: 1.29,
        NSFontAttributeName: UIFont.buttonFont()!,
        NSForegroundColorAttributeName: UIColor.whiteColor(),
    ]
}

This is disconnected from mine AppDelegate.

Now when you try to install ActionBarView.appearance().titleTextAttributes = [ ... ], I get the following runtime error:

error while trying to set attirbutes text in custom uiview subclass

It should be noted that setting attributes to UINavigationBarworks without problems.

UINavigationBar :

/* You may specify the font, text color, and shadow properties for the title in the text attributes dictionary, using the keys found in NSAttributedString.h.
 */
@available(iOS 5.0, *)
public var titleTextAttributes: [String : AnyObject]?

, ActionBarView:

class ActionBarView: UIView {

    var titleTextAttributes: [String : AnyObject]?

    // ...
}

, : - UIView, UIAppearance proxy? UI_APPEARANCE_SELECTOR Swift? UIKit, UINavigationBar? - ?

+4
2

, titleTextAttributes dynamic , :

class ActionBarView: UIView {

    /// UIAppearance compatible property
    dynamic var titleTextAttributes: [String : AnyObject]? { // UI_APPEARANCE_SELECTOR
        get { return self._titleTextAttributes }
        set { self._titleTextAttributes = newValue }
    }

    private var _titleTextAttributes: [String : AnyObject]?

    // ... use `self.titleTextAttributes` in the implementation
}
+1

:

class ActionBarView: UIView {

    dynamic var titleTextAttributes: [String : AnyObject] = [:]

    // use ActionBarView.appearance().titleTextAttributes 
}

:

func propertyForAxis1(axis1: IntegerType, axis2: IntegerType, axisN: IntegerType) -> PropertyType
func setProperty(property: PropertyType, forAxis1 axis1: IntegerType, axis2: IntegerType)
+3

Source: https://habr.com/ru/post/1648673/


All Articles