当前位置 : 主页 > 手机开发 > 其它 >

将属性文本设置为UIButton

来源:互联网 收集:自由互联 发布时间:2021-06-11
我正在尝试将属性字符串设置为按钮. swift上这个函数的定义就是这个 func setAttributedTitle(_ title: NSAttributedString!, forState state: UIControlState) 所以我想我必须输入它 myButton.setAttributedTitle(tit
我正在尝试将属性字符串设置为按钮.

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)
网友评论