Several classes in my app do the same thing and have the same instance variables:
// one of the many classes I have
// they all load nibs and update the frames of their views
class HelpView: UIView {
#IBOutlet var view: UIView!
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)!
NSBundle.mainBundle().loadNibNamed("HelpView", owner: self, options: nil)
self.addSubview(self.view)
self.view.frame = self.bounds
}
}
I want to avoid duplicated code, so I thought about using a superclass so that all the classes inherit from it.
// my new superclass all classes will inherit from
class ReusableView: UIView {
#IBOutlet var view: UIView! // all subclasses have different views
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)!
// every class has a different nib name
NSBundle.mainBundle().loadNibNamed("Nib name goes here", owner: self, options: nil)
self.addSubview(self.view)
self.view.frame = self.bounds
}
}
The problem is that view is nil until the nib is loaded, so it's apparently not possible to call that superclass' method because you're passing a nil object. How can I handle this?
This will work:
class ReusableView: UIView {
func getHelperView() -> UIView! {
preconditionFailure("This method must be overridden")
}
func getNibName() -> String {
preconditionFailure("This method must be overridden")
}
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)!
// every class has a different nib name
NSBundle.mainBundle().loadNibNamed(self.getNibName(), owner: self, options: nil)
self.addSubview(self.getHelperView())
self.getHelperView().frame = self.bounds
}
}
class HelpView: ReusableView {
#IBOutlet var view: UIView!
override func getHelperView() -> UIView! {
return view;
}
override func getNibName() -> String {
return "NibName";
}
}
Related
This AssetRFPViewController class call a custom view(AssetBasicInfo) in viewDidLoad, if a pass "Hello" its ok but when i pass object to custom view(AssetBasicInfo) its not taken, How can i design a custom view class so its catch object
class AssetRFPViewController: UIViewController
{
var asset:Asset = Asset()
override func viewDidLoad() {
let customView = AssetBasicInfo(frame: self.topHeaderView.bounds)
customView.assetNameValLbl.text = "Hello" // ok
customView.assetObj = self.asset // not ok, passing object
self.topHeaderView.addSubview(customView)
}
}
Now my custom class look like this,
class AssetBasicInfo: UIView {
#IBOutlet var containerView: UIView!
var assetObj:Asset = Asset() // i want value in this object "assetObj"
#IBOutlet var assetNameValLbl: UILabel!
override init(frame: CGRect) {
super.init(frame: frame)
print(frame.size.width)
print(frame.size.height)
commonInit()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder : aDecoder)
commonInit()
}
private func commonInit(){
Bundle.main.loadNibNamed("HeaderViewXIB", owner: self, options: nil)
self.addSubview(containerView)
self.containerView.frame = self.frame
containerView.autoresizingMask = [.flexibleHeight, .flexibleWidth]
self.assetNameValLbl.text = assetObj.name // not setting value
print("screenName" , screenName)
}
}
I have been trying to figure this out for days and haven't had much luck :(
What I want to do is set the variable inside of an instance of a XIB (called BottomNav) that already exists in another ViewController, called "curX". I have come the closest with the following:
class Util: NSObject {
class func loadNib() {
let nib: BottomNav = Bundle.main.loadNibNamed("BottomNav", owner: self, options: nil)!.first as! BottomNav
nib.curX = 10
}
}
Here is the BottomNav Class:
class BottomNav: UIView {
#IBOutlet var view: UIView!
#IBOutlet weak var homeBtn: UIView!
#IBOutlet weak var scroller: UIScrollView!
#IBOutlet weak var scrollerContent: UIView!
var curX = 32
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)!
Bundle.main.loadNibNamed("BottomNav", owner: self, options: nil)
self.addSubview(self.view)
}
}
This passes the compiler with no warnings, but when it's ran I get a "this class is not key value coding-compliant for the key" error. This usually appears when there's an outlet that no longer exists, but this is definitely not the case, I've tested it with multiple XIBs that are already on the app, and had no problem loading in the first place via storyboards. I only get this error with "loadNibNamed".
Am I even on the right path here? My thought is maybe my Util class doesn't have access to Bundle or something?
class BottomNav: UIView {
#IBOutlet var view: UIView!
#IBOutlet weak var homeBtn: UIView!
#IBOutlet weak var scroller: UIScrollView!
#IBOutlet weak var scrollerContent: UIView!
var curX = 32
override init(frame: CGRect) {
super.init(frame: frame)
commonInit()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
commonInit()
}
func commonInit(){
Bundle.main.loadNibNamed("BottomNav", owner: self, options: nil)
guard let content = view else { return }
content.frame = self.bounds
content.autoresizingMask = [.flexibleHeight, .flexibleWidth]
self.addSubview(content)
}
}
And when calling the instance, try the following.
let instance = BottomNav()
instance.curX = 30
Swift 3.0
I Think you get you solution from this. All the best
var view: UIView!
override init(frame: CGRect) {
// call super.init(frame:)
super.init(frame: frame)
// 3. Setup view from .xib file
xibSetup()
}
required init?(coder aDecoder: NSCoder) {
// call super.init(coder:)
super.init(coder: aDecoder)
// 3. Setup view from .xib file
xibSetup()
}
// MARK: - UI setup
func xibSetup() {
let nib = UINib(nibName: "BottomNav", bundle: nil)
view = nib.instantiate(withOwner: self, options: nil)[0] as! UIView
// use bounds not frame or it'll be offset
view.frame = bounds
// Make the view stretch with containing view
view.autoresizingMask = [UIViewAutoresizing.flexibleWidth, UIViewAutoresizing.flexibleHeight]
addSubview(view)
}
What is wrong with the following code, it's seems to have an endless loop. Initially comes through init:frame, to commonInit, but then the XIB loading line triggers entering again through init:coder etc.
Two areas of question:
a) How to instantiate probably to avoid this problem (i.e. want to use the XIB to layout, but then dynamically creating/position multiple of these on a parent view in code)
b) setting self.label.text is problematic as it seems self.label (a UILabel linked to the XIB) hasn't been setup at this point, hence is nil. So dynamically, when I want to create this little custom UIView via XIB, add it as a subclass, then immediately set a value of the label how do I do this?
import UIKit
class DirectionInfoView: UIView {
#IBOutlet weak var label: UILabel!
func commonInit() {
let viewName = "DirectionInfoView"
let view: DirectionInfoView = NSBundle.mainBundle().loadNibNamed(viewName, owner: self, options: nil).first as! DirectionInfoView // <== EXC_BAD_ACCESS (code=2...)
self.addSubview(view)
view.frame = self.bounds
self.label.text = "testing 123"
}
override init(frame: CGRect) {
super.init(frame: frame)
commonInit()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
commonInit()
}
}
Usage:
let newInfoView = DirectionInfoView(frame: self.mapview.bounds)
myexitingView.addSubview(newInfoView)
This seems to work:
import UIKit
class DirectionInfoView: UIView {
#IBOutlet weak var label: UILabel!
func commonInit() {
self.layer.borderWidth = 5
self.layer.cornerRadius = 25
}
override init(frame: CGRect) {
super.init(frame: frame)
commonInit()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
commonInit()
}
}
Usage:
let directionInfoView : DirectionInfoView = NSBundle.mainBundle().loadNibNamed("DirectionInfoView", owner: self, options: nil).first as! DirectionInfoView
mapview.addSubview(directionInfoView)
directionInfoView.label.text = "It Worked!"
All,
I have a bar button item on my ViewController. I have set a computed property to will turn the BarButton off. I want to be able to set this from another class.
Here is my code in the view controller :
class ViewController: UIViewController {
var PayButton : Int {
didSet {
navigationItem.leftBarButtonItem = nil
}
}
required init(coder aDecoder: NSCoder)
{
self.PayButton = 0
super.init(coder: aDecoder)
}
When it try and create an instance on the view controller (so I can set the PayButton integer)
let test = ViewController()
I get an error saying
Missing Argument for parameter 'coder' in call
Any ideas ?
It is asking for the parameter 'coder', because you have it in the required init.
To use your code as it stands, you would need to initialise with:
let test = ViewController(coder: NSCoder)
There are several ways to get around this. The easiest would be to remove the required initialiser.
import UIKit
class ViewController: UIViewController {
var PayButton : Int = 0 {
didSet {
navigationItem.leftBarButtonItem = nil
}
}
}
and then implement with
let test = ViewController()
test.PayButton = 0
Because you have implemented the required initializer in ViewController class.
There are two solutions
Add a default initializer
init() {
super.init(nibName: nil, bundle:nil)
}
Remove the required initializer.
class ViewController: UIViewController {
var PayButton : Int {
didSet {
navigationItem.leftBarButtonItem = nil
}
}
init() {
self.PayButton = 0
super.init(nibName: nil, bundle:nil)
}
required init(coder aDecoder: NSCoder)
{
self.PayButton = 0
super.init(coder: aDecoder)
}
Try this:
This is the required initializer:
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
This is the super initializer:
override init(frame: CGRect) {
super.init(frame: frame)
}
This is your convenience initializer where you can pass the size the view you want to create
convenience init(view: UIView){
self.init(frame: view.frame)
}
This is your convenience initializer where the view is initialized with a value pre defined:
convenience init(){
self.init(frame: CGRectZero) //Put you predefined value here
}
Something strange going on with IBOutlets.
In code I've try to access to this properties, but they are nil. Code:
class CustomKeyboard: UIView {
#IBOutlet var aButt: UIButton!
#IBOutlet var oButt: UIButton!
class func keyboard() -> UIView {
let nib = UINib(nibName: "CustomKeyboard", bundle: nil)
return nib.instantiateWithOwner(self, options: nil).first as UIView
}
override init() {
super.init()
commonInit()
}
override init(frame: CGRect) {
super.init(frame: frame)
commonInit()
}
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
commonInit()
}
// MARK: - Private
private func commonInit() {
println(aButt)
// aButt is nil
aButt = self.viewWithTag(1) as UIButton
println(aButt)
// aButt is not nil
}
}
That's expected, because the IBOutlet(s) are not assigned by the time the initializer is called.
Instead of calling commonInit() in init(coder:), do that in an override of awakeFromNib as follows:
// ...
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override func awakeFromNib() {
super.awakeFromNib()
commonInit()
}
// ...
Assuming you tried the standard troubleshooting steps for connecting IBOutlets, try this:
Apparently, you need to disable awake from nib in certain runtime cases.
override func awakeAfter(using aDecoder: NSCoder) -> Any? {
guard subviews.isEmpty else { return self }
return Bundle.main.loadNibNamed("MainNavbar", owner: nil, options: nil)?.first
}
Your nib may not be connected. My solution is quite simple. Somewhere in your project (I create a class called UIViewExtension.swift), add an extension of UIView with this handy connectNibUI method.
extension UIView {
func connectNibUI() {
let nib = UINib(nibName: String(describing: type(of: self)), bundle: nil).instantiate(withOwner: self, options: nil)
let nibView = nib.first as! UIView
nibView.translatesAutoresizingMaskIntoConstraints = false
self.addSubview(nibView)
//I am using SnapKit cocoapod for this method, to update constraints. You can use NSLayoutConstraints if you prefer.
nibView.snp.makeConstraints { (make) -> Void in
make.edges.equalTo(self)
}
}
}
Now you can call this method on any view, in your init method, do this:
override init(frame: CGRect) {
super.init(frame: frame)
connectNibUI()
}
Building on #ScottyBlades, I made this subclass:
class UIViewXib: UIView {
// I'm finding this necessary when I name a Xib-based UIView in IB. Otherwise, the IBOutlets are not loaded in awakeFromNib.
override func awakeAfter(using aDecoder: NSCoder) -> Any? {
guard subviews.isEmpty else { return self }
return Bundle.main.loadNibNamed(typeName(self), owner: nil, options: nil)?.first
}
}
func typeName(_ some: Any) -> String {
return (some is Any.Type) ? "\(some)" : "\(type(of: some))"
}
There is possibility that you not mentioned the FileOwner for xib.
Mention its class in File owner not in views Identity Inspector .
And how did you initiate your view from the controlller? Like this:
var view = CustomKeyboard.keyboard()
self.view.addSubview(view)