Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/ios/115.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ios 如何在Swift中通过标签访问UIButton_Ios_Uibutton_Swift - Fatal编程技术网

Ios 如何在Swift中通过标签访问UIButton

Ios 如何在Swift中通过标签访问UIButton,ios,uibutton,swift,Ios,Uibutton,Swift,目标-C UIButton *tmpButton = (UIButton *)[self.view viewWithTag:tmpTag]; 如何在Swift中进行此操作?在Swift中,此操作如下所示: var tmpButton = self.view.viewWithTag(tmpTag) as? UIButton 它或多或少是一种直接翻译,除了cast位于表达式的另一端。转到Swifty as a C-into-swift converter,使用此选项转换代码并获得答案 目标C代码

目标-C

UIButton *tmpButton = (UIButton *)[self.view viewWithTag:tmpTag];

如何在Swift中进行此操作?

在Swift中,此操作如下所示:

var tmpButton = self.view.viewWithTag(tmpTag) as? UIButton

它或多或少是一种直接翻译,除了cast位于表达式的另一端。

转到Swifty as a C-into-swift converter,使用此选项转换代码并获得答案

目标C代码

UIButton *tmpButton = (UIButton *)[self.view viewWithTag:tmpTag];
Swift代码

let tmpButton = view.viewWithTag(tmpTag) as? UIButton

我自己做的
var sasaButton=self.view.viewWithTag(22)作为UIButton
它与您的相同,但只是没有
。那么,您能告诉我您的代码中有什么
。@WebOrCode我使用
使变量成为可选变量,以防标记视图不存在。如果您100%确定标记的视图在那里,则可以删除
。@webOrCode在Swift 2.0中您必须使用!或用于展开。为什么按钮的标记不能为=0<代码>var tmpButton=self.view.viewWithTag(0)as?UIButton
print(tmpButton)//输出:nil
@HassanTaleb是标记为零的控件,而不是
UIButton
?此解决方案实际上与公认的答案相同,因此否决它是不公平的。我发现它比公认的答案更有趣,因为它建议使用名为Swiftify的工具进行Objective-C到Swift的翻译。这个答案和公认答案之间一个有趣的区别是它省略了
self
。我检查了它在没有
self
的情况下是否还能工作,它确实工作了。根据Ray Wenderlich的样式指南,只要编译器接受self,就应该省略它