swift-将值分配给子视图中的自定义按钮

问题描述:

您好我想分配for循环中的自定义按钮中的特定子视图它在目标c中正常工作,但我在swift代码中遇到问题。swift-将值分配给子视图中的自定义按钮

目标的C代码:

HButton *view = nil; // hbutton class object 
    NSArray *subviews = [self.superview subviews]; // storing the subviews in subviews array 
    NSInteger i = 0; // for index 
    for (view in subviews) 
    { 
      if ([view isKindOfClass:[HButton class]]) 
      { 
       HButton *check=[subviews objectAtIndex:i]; 
      if (self.tag == check.tag) 
      { 
        self.titleLabel.text [email protected]"hel"; 
        self.backgroundColor =[UIColor orangeColor]; 
      } 
     i++; 
    } 

Swift代码:

var view1 :BTNCustom! = nil 
    var subviews : NSArray = self.superview.subviews 

    var ival : Int = 0; 
    for view1 : AnyObject in subviews // I'm getting the error in this line 
    { 
    if view1.isKindOfClass(BTNCustom) 
    { 
    var check : BTNCustom = subviews.objectAtIndex(ival) as BTNCustom 
    if (self.tag == check.tag) 
{ 
self.titleLabel.text = "hel"; 
self.backgroundColor = UIColor.orangeColor() 
} 
ival++; 
} 
} 
+0

“我收到错误”请注明您收到的错误 – newacct

+0

您收到什么错误? –

你能更清楚你实际上是想干什么?以下是我能想象到你正在尝试做的最接近的事:

for view in superview.subviews { 
    if view.isKindOfClass(BTNCustom) && tag == view.tag { 
    titleLabel.text = "hel" 
    backgroundColor = UIColor.orangeColor() 
    } 
} 

然而,它真的看起来像你在滥用标签,并没有真正理解一个类型系统的点。

具体问题与您的代码:

1)var view1 :BTNCustom! = nil你是,你是说你想成为自动解包,为什么不直接var view1: BTNCustom!,他们应该是相同的,但后面的这些东西分配零得多可口。

2)当您已经声明它为BTNCustom时,您试图使用view1作为您的不同类型的循环变量。为什么?你真的使用这样的变量名吗?你有限制你允许使用的字符数量吗?

3)使用一个额外的整数将视图拉出子视图数组的时候,实际上该视图恰好是您已经参考的视图,这是什么意思?清楚的是,在您的Obj-C代码中,无论您何时使用checkviewcheck都将始终保持一致。

只是试图解决你的错误,这可能会帮助你!

for index in 1...subviews 
{ 
    let view1:AnyObject = subViews[index] as AnyObject 
    if view1.isKindOfClass(BTNCustom) 
    { 
      var check : BTNCustom = subviews.objectAtIndex(ival) as BTNCustom 
      if (self.tag == check.tag) 
      { 
       self.titleLabel.text = "hel"; 
       self.backgroundColor = UIColor.orangeColor() 
      } 
      ival++; 
    } 
}