最新消息:20210917 已从crifan.com换到crifan.org

[已解决]Swift代码出错:Cannot convert value of type UIView? to specified type UIButton

Swift crifan 3248浏览 0评论
[问题]
ObjC代码:
 UIButton *fromButton = (UIButton *)[tabButtonsContainerView viewWithTag:TagOffset + _selectedIndex];

转换为swift:

        for viewController in self.viewControllers{
            let button:UIButton = UIButton(type: UIButtonType.Custom)
            。。。
            tabButtonsContainerView!.addSubview(button)
            。。。
        }

let fromButton:UIButton = tabButtonsContainerView?.viewWithTag(TagOffset + Int(_selectedIndex))
结果报错:
Cannot convert value of type ‘UIView?’ to specified type ‘UIButton’
如图:
Cannot convert value of type UIView to specified type UIButton
[解决过程]
1.改为:
let fromButton:UIButton = UIButton(tabButtonsContainerView?.viewWithTag(TagOffset + Int(_selectedIndex)))
报错:
Cannot invoke initializer for type ‘UIButton’ with an argument list of type ‘(UIView?)’
2.搜:
swift Cannot convert value of type UIView? to specified type UIButton
参考:
3.搜:
swift   convert   UIView? to UIButton
参考:
4.自己去摸索:
看到UIButton的初始化有几种:
several init for UIButton
也去看了UIButton的继承关系:
public class UIButton : UIControl {
public class UIControl : UIView {
然后也看到官网文档:
解释了:
  •  – NSObject
    • – UIResponder
      • – UIView
        • – UIControl
          • – UIButton
5.搜:
swift uiview downcast
参考:
6.参考;
Looping through subviews and downcasting in Swift — timbroder.com
想起来了:
好像估计是搞清楚那个:
is,as,as?
之类的用法,或许就可以去使用as,强制转换了此处的UIView为UIButton了?
改为:
let fromButton:UIButton = tabButtonsContainerView!.viewWithTag(TagOffset + Int(_selectedIndex)) as UIButton
然后提示:
 ‘UIView?’ is not convertible to ‘UIButton’; did you mean to use ‘as!’ to force downcast?
UIView  is not convertible to UIButton did you mean to use as to force downcast
所以就换成:
let fromButton:UIButton = tabButtonsContainerView!.viewWithTag(TagOffset + Int(_selectedIndex)) as! UIButton
即可通过编译。
此时,也知道了:
as!叫做force downcast
-》
as应该就是叫做downcast
[总结]
此处,对于本身UIView的tabButtonsContainerView,之前已经添加进去的多个UIButton,去获取对应的UIView后,想要转换为UIButton,直接赋值给UIButton会出错。
解决办法是:
用as!去实现,强制转换,将UIView强制认为是UIButton(因为之前本来就是UIButton,所以这种转换,是没有问题的)
代码如下:
let fromButton:UIButton = tabButtonsContainerView!.viewWithTag(TagOffset + Int(_selectedIndex)) as! UIButton
供参考。
[后记]
即使表面解决了此问题,也要去搞清楚as和is等参数的含义:

转载请注明:在路上 » [已解决]Swift代码出错:Cannot convert value of type UIView? to specified type UIButton

发表我的评论
取消评论

表情

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址
96 queries in 0.194 seconds, using 23.34MB memory