Getting SIGABRT in custom uiview using xib in Xcode 6 using Swift

我与影子孤独终老i 提交于 2019-12-24 17:13:02

问题


I have created a custom view with two labels by following some tutorials online. I have connected the custom xib to the swift class file with outlets for the two labels. When I initialise the view from the view controller where I need to present the view, I am getting a SIGABRT error on the line

let view = nib.instantiateWithOwner(self, options: nil)[0] as! UIView

The code for the custom view class is as follows:

import UIKit

@IBDesignable class LevelButton: UIView {

    @IBOutlet weak var levelLabel: UILabel!
    @IBOutlet weak var score: UILabel!
    var view:UIView!
    var levelLabelText:String?
    {
            get
            {
                return levelLabel.text
        }
        set(levelLabelText)
        {
            levelLabel.text = levelLabelText
        }
    }

    var scoreText:String?
        {
        get{
            return score.text
        }
        set(scoreText)
        {
            score.text = scoreText
        }
    }

    override init(frame: CGRect) {
        super.init(frame: frame)
        setup()
    }
    required init(coder aDecoder:NSCoder)
    {
        super.init(coder: aDecoder)
        setup()
    }

    func setup()
    {
        view = loadViewFromNib()
        view.frame = bounds
        view.autoresizingMask = UIViewAutoresizing.FlexibleWidth | UIViewAutoresizing.FlexibleHeight
        addSubview(view)
    }
    func loadViewFromNib() -> UIView
    {
        let bundle = NSBundle(forClass: self.dynamicType)
        let nib = UINib(nibName: "LevelButton", bundle: bundle)
        let view = nib.instantiateWithOwner(nil, options: nil)[0] as! UIView
        return view
    }

}

In the main storyboard, I added a view and set its custom class to the class with the above code, but it does not show anything and gives a SIGABRT error.

I am unable to figure out a solution. Please suggest (Swift only).


回答1:


This may be a solution for your question:

Change this function:

func setup()
{
    view = loadViewFromNib()
    view.frame = bounds
    view.autoresizingMask = UIViewAutoresizing.FlexibleWidth | UIViewAutoresizing.FlexibleHeight
    addSubview(view)
}

to:

func setup() {

    if self.subviews.count == 0 {
        view = loadViewFromNib()
        view.frame = bounds
        view.autoresizingMask = UIViewAutoresizing.FlexibleWidth | UIViewAutoresizing.FlexibleHeight
        addSubview(view)
    }

}

Source from: http://blog.boxuanzhang.me/custom-reusable-uiview-with-xib/



来源:https://stackoverflow.com/questions/32354844/getting-sigabrt-in-custom-uiview-using-xib-in-xcode-6-using-swift

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!