Swift 中的 UIControlState

Posted

技术标签:

【中文标题】Swift 中的 UIControlState【英文标题】:UIControlState in Swift 【发布时间】:2015-06-01 11:43:11 【问题描述】:

这是我的代码:

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

我有一个错误“在最后一行找不到成员'正常'。怎么了?

【问题讨论】:

【参考方案1】:

您需要将attributes 转换为[NSObject : AnyObject],您的代码将是:

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

这是Apple Docs的默认语法:

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

或者您可以在创建时将attributes 转换为[NSObject : AnyObject]?,代码代码将为:

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

【讨论】:

【参考方案2】:

它应该适用于您的代码。您只需重新启动您的 xcode。

试试吹码:

import UIKit

class ViewController: UIViewController 

    @IBOutlet var segment: UISegmentedControl!

    override func viewDidLoad() 
        super.viewDidLoad()


        let font = UIFont(name: "AvenirNext-Regular", size: 26.0)
        let attributes: NSDictionary? = [ NSFontAttributeName : font! ]
       segment.setTitleTextAttributes(attributes! as [NSObject : AnyObject], forState:.Normal)

        // Do any additional setup after loading the view, typically from a nib.
    

    override func didReceiveMemoryWarning() 
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    


【讨论】:

【参考方案3】:

更改以下代码行:

self.segmentedControl.setTitleTextAttributes(attributes, forState:.Normal)

到这里:

self.segmentedControl.setTitleTextAttributes(attributes, forState: UIControlState.normal)

或者您也可以使用以下内容:

self.segmentedControl.setTitleTextAttributes(attributes as? [AnyHashable : Any], forState: UIControlState.normal)

【讨论】:

以上是关于Swift 中的 UIControlState的主要内容,如果未能解决你的问题,请参考以下文章

swift: Swift 中的 SnapKit 不起作用

swift中的 isKindofClass

swift Swift中的变量

swift Swift中的数组

swift SWIFT中的变量

swift Swift4中的Codable