2015-09-02 47 views
1

我已經通過在線一些教程創建了具有兩個標籤的自定義視圖。我已將定製的xib連接到帶有兩個標籤的插座的swift類文件。當我初始化從視圖控制器我需要呈現視圖的視圖,我收到上線一個SIGABRT錯誤使用Swift在Xcode 6中使用xib在自定義uiview中獲取SIGABRT

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

自定義視圖類的代碼如下:

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 
    } 

} 

在主要故事板中,我添加了一個視圖並使用上面的代碼將其自定義類設置爲類,但它不顯示任何內容並且出現SIGABRT錯誤。

我無法找出解決方案。請建議(僅限Swift)。

回答

0

這可能是你的問題的解決方案:

更改此功能:

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

到:

func setup() { 

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

} 

資料來源:http://blog.boxuanzhang.me/custom-reusable-uiview-with-xib/

相關問題