Getting SIGABRT in custom uiview using xib in Xcod

2019-08-10 06:41发布

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条回答
你好瞎i
2楼-- · 2019-08-10 06:52

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/

查看更多
登录 后发表回答