简体   繁体   中英

Custom UIView without Storyboard

Now I'm practicing build IOS app without using storyboard , but I have a problem want to solve , I created a custom UIView called BannerView and added a background(UIView) and a title(UILabel) , and called this BannerView in the MainVC , but run this app , it crashes at the function setupSubviews() and I don't know why.

import UIKit
import SnapKit

class BannerView: UIView {

    var background: UIView!
    var title: UILabel!

    override init(frame: CGRect) {
        super.init(frame: frame)
        setupSubviews()
    }

    convenience init() {
        self.init(frame: CGRect.zero)
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        setupSubviews()
    }

    func setupSubviews() {
        background.backgroundColor = .gray
        title.text = "INHEART"

        self.addSubview(background)
        self.addSubview(title)
    }

    override func layoutSubviews() {
        background.snp.makeConstraints { make in
            make.width.equalTo(ScreenWidth)
            make.height.equalTo(BannerHeight)
            make.left.top.right.equalTo(0)
        }

        title.snp.makeConstraints { make in
            make.width.equalTo(100)
            make.center.equalTo(background.snp.center)
        }
    }

}




class MainVC: UIViewController {

    var bannerView:BannerView!

    override func viewDidLoad() {
        super.viewDidLoad()
        bannerView = BannerView(frame: CGRect.zero)
        view.addSubview(bannerView)
    }

}

Your properties do not appear to be initialised

var background: UIView!
var title: UILabel!

You should initialize these in your init method

self.background = UIView()
self.title = UILabel()

If you use force unwrapping on a class property you must initialize in the init method. XCode should be complaining to you about this and your error message should show a similar error

You are not initialised the background view please initialised them

self.background = UIView()
self.title = UILabel()

and if you want to create custom view by use of xib the follow them Custum View

You must have to initialised the self.background = UIView() and self.title = UILabel() first.

You can initalised them in setupSubviews() function before the set/assign values to them.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM