微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

将属性文本设置为UIButton

我正在尝试将属性字符串设置为按钮.

swift上这个函数的定义就是这个

func setAttributedTitle(_ title: NSAttributedString!,forState state: UIControlState)

所以我想我必须输入它

myButton.setAttributedTitle(title:attrString,forState: UIControlState.normal)

但是正确的是

myButton.setAttributedTitle(attrString,forState: UIControlState.normal)

为什么有必要把国家:但不是标题?我不明白.

顺便说一下func定义中下划线的含义是什么?

解决方法

因为这就是方法参数在swift中的工作方式.我强调方法,因为这不适用于裸函数,即类范围之外的函数定义.

认情况下,第一个参数没有显式名称,而其他名称则是必需的.

official guide

Methods in Swift are very similar to their counterparts in Objective-C. As in Objective-C,the name of a method in Swift typically refers to the method’s first parameter using a preposition such as with,for,or by,as seen in the incrementBy method from the preceding Counter class example. The use of a preposition enables the method to be read as a sentence when it is called. Swift makes this established method naming convention easy to write by using a different default approach for method parameters than it uses for function parameters.

Specifically,Swift gives the first parameter name in a method a local parameter name by default,and gives the second and subsequent parameter names both local and external parameter names by default. This convention matches the typical naming and calling convention you will be familiar with from writing Objective-C methods,and makes for expressive method calls without the need to qualify your parameter names.

下划线表示:此参数没有外部参数名称.对于方法的第一个参数,这是多余的,但您可以使用它来更改上面讨论的认行为.

例如

class Foo {
    func bar(a: String,b: Int) {}
    func baz(a: String,_ b: Int) {}
}

将导致以下正确使用方法调用

var f = Foo()
f.bar("hello",b: 1)
f.baz("hello",1)

添加_具有使b成为本地名称效果,因此您无法做到

f.baz("hello",b: 1)

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐