swiftuicontrolstate

UIControlState in Swift


Here is my code:

let font = UIFont(name: "AvenirNext-Regular", size: 16.0)
let attributes: NSDictionary? = [ NSFontAttributeName : font! ]
self.segmentedControl.setTitleTextAttributes(attributes, forState:.Normal)

I have an error "Could not find member 'Normal' in the last line. What's wrong?


Solution

  • You need to cast your attributes to [NSObject : AnyObject] and your code will be :

    segmentedControl.setTitleTextAttributes(attributes as [NSObject : AnyObject]?, forState: .Normal)
    

    This is default syntax from Apple Docs:

    func setTitleTextAttributes(_ attributes: [NSObject : AnyObject]?, forState state: UIControlState)
    

    Or you can cast attributes to [NSObject : AnyObject]? when you create it and code code will be:

    let font = UIFont(name: "AvenirNext-Regular", size: 16.0)
    let attributes: [NSObject : AnyObject]? = [ NSFontAttributeName : font! ]
    self.segmentedControl.setTitleTextAttributes(attributes, forState: UIControlState.Normal)