gpt4 book ai didi

uibutton - 将属性文本设置为 UIButton

转载 作者:搜寻专家 更新时间:2023-10-31 19:31:46 26 4
gpt4 key购买 nike

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

这个函数在swift上的定义是这样的

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

所以我想我必须这样输入

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

但是正确的是

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

为什么要放forState:而不是title?我不明白。

顺便问一下,函数定义中的下划线是什么意思?

最佳答案

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

默认情况下,第一个参数没有明确的名称,这对其他参数来说是强制性的。

来自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)

关于uibutton - 将属性文本设置为 UIButton,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24148042/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com