performSegueWithIdentifier不适用于以编程方式生成的UIButtons(iOS / Swift)

时间:2015-07-31 02:49:47

标签: swift

Xcode 6,Swift,iOS8

我有一个由动态生成的UIButton填充的视图控制器。按钮的数量取决于数据馈送,而不是静态的。我计算了Feed中的对象数量,并为每个对象生成一个按钮。每个按钮都应该进入细节视图,显示其相应对象的信息。

在Interface Builder中,我在两个视图控制器之间创建了一个segue并命名它。我没有添加IBAction来启动segue,因为我无法将其绑定到特定按钮。

在View Controller Class中,我执行以下命令:

@IBOutlet weak var localScrollView: UIScrollView! 


override func viewDidLoad() {
    super.viewDidLoad()

//Define the button dimensions
    let buttonWidth:CGFloat = 200
    let buttonHeight:CGFloat = 113

    var xPos:CGFloat = 0
    var scrollViewContent:CGFloat = 0
    var thumbURL:String

//keeps track of the number of videos. The count is used to set a tag on the button to help identify it.
    var vidCount:Int = 0  

    //loop through the array of recommended video objects
    for index in recommended{

   //Create a button for each object 
       var myButton = UIButton.buttonWithType(UIButtonType.System) as! UIButton

        myButton.frame = CGRectMake(xPos, 0.0, buttonWidth, buttonHeight)

    //For the button action I call the handleTap function detailed below
        myButton.addTarget(self, action: "handleTap:", forControlEvents: .TouchUpInside)

        myButton.tag = vidCount

    //The image for the button is pulled from a CDN. This code sets the image in the button.
        let curVal = index.thumbURL
        if let url = NSURL(string: curVal) {
            if let data = NSData(contentsOfURL: url){

                myButton.setBackgroundImage(UIImage(data:data), forState: UIControlState.Normal)

            }
        }

    //add the button to the scroll view
        localScrollView.addSubview(myButton)

        let spacer:CGFloat = 10
        xPos+=buttonWidth + spacer
        scrollViewContent += buttonWidth + spacer

        localScrollView.contentSize = CGSize(width: scrollViewContent, height: buttonHeight)
        vidCount += 1

    }


}


//function to handle the tap action
func handleTap(sender:UIButton){

    //Set the variable that will be passed to the next view controller
    curRecVid = recommended[sender.tag]

    //initiate the segue
    dispatch_async(dispatch_get_main_queue()) {
        self.performSegueWithIdentifier("toSingle", sender: self)
    }

}

//prepare the data to be transferred to the next view controller
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject!) {
    if (segue.identifier == "toSingle") {
        var targetViewController = segue.destinationViewController as! SingleViewController
        targetViewController.targetVid = curRecVid

    }
}

}

当我在模拟器中运行应用程序时,它会进入self.performSegueWithIdentifier(“toSingle”,sender:self)调用,然后终止到以下未捕获的异常:'NSInvalidArgumentException',原因:' - [UILabel copyWithZone: ]:无法识别的选择器发送到实例0x7fd468c8ddc0'

非常感谢帮助追踪此异常原因的任何帮助。

1 个答案:

答案 0 :(得分:0)

目标View Controller的类文件似乎存在某种问题。在Epic Defeater的评论之后,我删除了它的swift文件,重新生成它并输入完全相同的代码(字面意思是,复制/粘贴),这就是诀窍。