IBAction for UIButton with it's own .xib file - ios

I want to create a reusable button all over my app and was planning to design it with it's own .xib file. The issue is that I can't connect an IBAction to the custom button in the controllers where it's used.
I created a new .xib file called SampleButton.xib and added a button. This is what the hierarchy and the view looks like:
I then created a new swift file called SampleButton.swift with a class called SampleButton that's a subclass of UIButton and assigned it as the File's Owner in my SampleButton.xib file.
The contents of SampleButton.swift are as follows:
import Foundation
import UIKit
#IBDesignable
class SampleButton: UIButton {
override init(frame: CGRect) {
super.init(frame: frame)
setup()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setup()
}
func setup() {
guard let view = loadViewFromNib() as? UIButton else {
return
}
view.frame = bounds
view.autoresizingMask = [UIView.AutoresizingMask.flexibleWidth,
UIView.AutoresizingMask.flexibleHeight]
addSubview(view)
view.layer.borderWidth = 2
view.layer.borderColor = UIColor.white.cgColor
}
func loadViewFromNib() -> UIView? {
let bundle = Bundle(for: type(of: self))
let nib = UINib(nibName: String(describing: type(of: self)), bundle: bundle)
return nib.instantiate(withOwner: self, options: nil).first as? UIButton
}
#IBAction func pressed(_ sender: Any) {
print("Called in here")
}
}
I can then create a new button in my storyboard and set it to custom and the class to SampleButton. However now if I ctrl + drag from my button to my corresponding View Controller to create an IBAction for the button, it's not called. The one in the SampleButton.swift file is. Even if I delete the IBAction in the SampleButton file it's still not called.
Any help here? I want to be able to design the buttons separately and then have IBactions for them in the controllers where they're used.

I encountered this same issue with some of my custom xib views and my initial thought was that I could set up my xib to be IBDesignable and then connect outlets from the storyboard rendering of my button in the view controller.
That didn't work.
So I setup a bit of a workaround using delegate callbacks from my custom views. I created IBOutlets for the view to the view controllers using them, then in viewDidLoad I'd set the delegate and handle the button tap in the view controller
import UIKit
// defines a callback protocol for the SampleButtonView
protocol SampleButtonViewDelegate: class {
func sampleButtonTapped(_ button: SampleButton)
}
#IBDesignable
class SampleButton: UIView, NibLoadable {
// create IBOutlet to button if you want to register a target/action directly
#IBOutlet var button: UIButton!
// set delegate if you want to handle button taps via delegate
weak var delegate: SampleButtonViewDelegate?
// initializers to make it so this class renders in view controllers
// when using IBDesignable
convenience init() {
self.init(frame: .zero)
}
override init(frame: CGRect) {
super.init(frame: frame)
loadFromNib(owner: self)
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
loadFromNib(owner: self)
}
#IBAction func buttonTapped(_ sender: Any) {
delegate?.sampleButtonTapped(_ button: self)
}
}
// here's a sample ViewController using this view and the delegate callback method
class ViewController: UIViewController {
#IBOutlet var sampleButtonView: SampleButton!
override func viewDidLoad() {
super.viewDidLoad()
sampleButtonView.delegate = self
}
}
extension ViewController: SampleButtonViewDelegate {
func sampleButtonTapped(_ button: SampleButton) {
// TODO: run logic for button tap here
}
}
For completeness I'll also add this NibLoadable protocol definition here.
// I used this for the #IBDesignable functionality to work and actually render
// my xib layouts in the storyboard view controller layouts using this class
import UIKit
/// Defines an interface for UIViews defined in .xib files.
public protocol NibLoadable {
// the name of the associated nib file
static var nibName: String { get }
// loads the view from the nib
func loadFromNib(owner: Any?)
}
public extension NibLoadable where Self: UIView {
/// Specifies the name of the associated .xib file.
/// Defaults to the name of the class implementing this protocol.
/// Provide an override in your custom class if your .xib file has a different name than it's associated class.
static var nibName: String {
return String(describing: Self.self)
}
/// Provides an instance of the UINib for the conforming class.
/// Uses the bundle for the conforming class and generates the UINib using the name of the .xib file specified in the nibName property.
static var nib: UINib {
let bundle = Bundle(for: Self.self)
return UINib(nibName: Self.nibName, bundle: bundle)
}
/// Tries to instantiate the UIView class from the .xib file associated with the UIView subclass conforming to this protocol using the owner specified in the function call.
/// The xib views frame is set to the size of the parent classes view and constraints are set to make the xib view the same size as the parent view. The loaded xib view is then added as a subview.
/// This should be called from the UIView's initializers "init(frame: CGRect)" for instantiation in code, and "init?(coder aDecoder: NSCoder)" for use in storyboards.
///
/// - Parameter owner: The file owner. Is usually an instance of the class associated with the .xib.
func loadFromNib(owner: Any? = nil) {
guard let view = Self.nib.instantiate(withOwner: owner, options: nil).first as? UIView else {
fatalError("Error loading \(Self.nibName) from nib")
}
view.frame = self.bounds
view.autoresizingMask = [.flexibleWidth, .flexibleHeight]
addSubview(view)
}
}
You could also simply register the functions you defined in your view controller as the target/action functions for the button in the custom view.
override func viewDidLoad() {
super.viewDidLoad()
mySampleButtonView.button.addTarget(self, action: #selector(buttonTapped(_:)), for: .touchUpInside)
}
#objc func buttonTapped(_ sender: UIButton) {
// handle button tap action in view controller here...
}

create iboutlet of button in nib class.
add you nib view in your viewcontroller where its needed.
add target for the button outlet.
try following code:
override func viewDidLoad() {
super.viewDidLoad()
let myButton = Bundle.main.loadNibNamed("myButtonxibName", owner: self, options: nil)?[0] as? myButtonxibClassName
myButton.button.addTarget(self, action: #selector(buttonTapped(_:)), for: .touchUpInside)
self.view.addsubview(myButton)
}
#objc func buttonTapped() {}

You don't need a Xib for what you're trying to do. Remove the loadViewFromNib() and the pressed(_ sender: Any) functions from your class above. Change your setup() method to customize your button. I see that you want to add a border to it. Do something like this:
func setup() {
self.layer.borderWidth = 2
self.layer.borderColor = UIColor.white.cgColor
// * Any other UI customization you want to do can be done here * //
}
In your storyboard, drag and drop a regular UIButton wherever you want to use it, set the class in the attributes inspector to SampleButton, connect your IBOutlet and IBActions as necessary, and it should be good to go.

I don't think it's possible to do this. Simpler way is to just set the target and action in view controllers. Something like:
class VC: UIViewController {
func viewDidLoad() {
sampleButton.addTarget(self, action: #selector(didClickOnSampleButton))
}
}

Related

How to make #IBAction from a custom view in storyboard?

I added a custom view, that has a button, to my viewController. I want to make an #IBAction from that button to my viewController.
I have following problems:
How do I make it show up in a storyboard? When I run the app it works fine.
How do I make an #IBAction from that button to my viewController?
class CustomCellView: UIView{
//MARK: Initializer
override func awakeFromNib() {
super.awakeFromNib()
}
override init(frame: CGRect) {
super.init(frame: frame)
commonInit()
}
required init?(coder: NSCoder) {
super.init(coder: coder)
commonInit()
}
override func prepareForInterfaceBuilder() {
super.prepareForInterfaceBuilder()
commonInit()
}
//MARK: Functions
func commonInit(){
let customView = Bundle.main.loadNibNamed("customCellView", owner: self, options: nil)?.first as? UIView ?? UIView()
customView.frame = self.bounds
self.addSubview(customView)
}
}
Add #objc in your viewController where you added customView.
e.g.
#objc func actionCustom()
{
print("Click Added")
}
Use
func commonInit(){
let customView = Bundle.main.loadNibNamed("customCellView", owner: self, options: nil)?.first as? UIView ?? UIView()
customView.frame = self.bounds
self.addSubview(customView)
customView.button.addTarget(self, action: #selector(actionCustom), for: .touchUpInside) //Add click code here
}
my customView is not showing in storyboard but when I run the app it's ok
This is the expected behaviour with the custom views. You won't get to see how the view looks in the xib that you use the custom view only in the xib that you defined the view.
How make #IBAction from that button to my viewController.
You can't. Custom views don't make public the subviews in interface builder. The best thing you can do is to use the delegate pattern or as Bhavesh Sarsawa pointed out doing it programatically either by adding the vc as a target or by making an IBAction in the ccustom view which calls a closure that is sent by dependency injection.
customButton.setAction { code that gets called when the button is pressed }

IBDesignable UI is not showing in Xcode 9 with Swift

I trying to using my custom xib files. But those UI are not showing in main view controller in xcode. But it show when run the app. I already added #IBDesignable in class. Here is what i did.
I created TestView.xib and added some design
I created TestView.swift
I updated fileOwner of TestView.xib with TestView in Custom Class
I added init code to testView.swift
Code inside TestView.swift
import UIKit
#IBDesignable class DetailView: UIView {
override init(frame: CGRect){
super.init(frame: frame)
self.setup()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)!
self.setup()
}
func setup() {
let view = Bundle.main.loadNibNamed("TestView", owner: self, options: nil)?.first as! UIView
view.frame = self.bounds
self.addSubview(view)
}
}
And Added on UIView in MainViewController and link to TestView with custom class name.
After that i run the app, I can see the UI from testView. Image of emulator and result
But my custom UI don't show in MainViewController in xcode Image of xcode view controller
How can i enable to see my custom UI in MainViewController ? Thanks
In InterfaceBuilder select your ViewController and choose "Editor-->Refresh all Views". Then your custom view should come up.
If something is wrong you can debug your IBDesignable class by setting breakpoints in your code and then choose "Editor-->Debug selected views".
prepareForInterfaceBuilder() only needs to be implemented if you need special design appearance in InterfaceBuilder.
Sometimes it is necessary to clean the project and build folder to get it to work:
Project->Clean
Project->(hold down options key)->Clean Build Folder
I just changed the setup function. It working now. Final Result Image - It showing UI in IB
func setup() {
view = loadViewFromNib()
view.frame = bounds
view.autoresizingMask = UIViewAutoresizing(rawValue: UIViewAutoresizing.RawValue(UInt8(UIViewAutoresizing.flexibleWidth.rawValue) | UInt8(UIViewAutoresizing.flexibleHeight.rawValue)))
self.addSubview(view)
}
func loadViewFromNib() -> UIView {
let bundle = Bundle(for: type(of: self))
let nib = UINib(nibName: "TestView", bundle: bundle)
let view = nib.instantiate(withOwner: self, options: nil)[0] as! UIView
return view
}
Override two func below for live:
override open func prepareForInterfaceBuilder() {
layer.cornerRadius = cornerRadius
layer.borderWidth = borderWidth
}
override open func awakeFromNib() {
layer.cornerRadius = cornerRadius
layer.borderWidth = borderWidth
}

Loading iOS view dynamically from xib file

Ive been searching for a while for a simple example on how to reuse views from xib files in my storyboard but all i find was outdated or dosen't solve my problem
the situation is that I has simple:
I have a viewController in my storyboard
I dragged to it two view from the library
I had created a myCustomView.xib and myCustomView.swift file (they are empty now)
I have I button on viewController (so the tree (two view and one button) are setting together on the viewController in the storyboard)
the question is: I want one view to be loaded dynamically on app launch and the other one to be loaded on button click
an other question: how can I connect myCustomView to that viewController
thank you
I've implemented an extension for UIView:
extension UIView {
static func createInstance<T: UIView>(ofType type: T.Type) -> T {
let className = NSStringFromClass(type).components(separatedBy: ".").last
return Bundle.main.loadNibNamed(className!, owner: self, options: nil)![0] as! T
}
}
In this way, wherever you can load your custom view in this way:
func override viewDidLoad() {
super.viewDidLoad()
let customView = UIView.createInstance(ofType: CustomView.self)
self.view.addSubview(customView)
}
Add bellow code in your custom view class
class MyCustomView: UIView {
#IBOutlet var contentView: UIView! // take view outlet
override init(frame: CGRect) {
super.init(frame: frame)
xibSetup()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
xibSetup()
}
func xibSetup() {
contentView = loadViewFromNib()
// use bounds not frame or it'll be offset
contentView!.frame = bounds
//Make the view stretch with containing view
contentView!.autoresizingMask = [UIViewAutoresizing.flexibleWidth, UIViewAutoresizing.flexibleHeight]
// Adding custom subview on top of our view (over any custom drawing > see note below)
addSubview(contentView!)
layoutIfNeeded()
}
override func layoutIfNeeded() {
super.layoutIfNeeded()
print("layoutIfNeeded")
}
func loadViewFromNib() -> UIView! {
let bundle = Bundle(for: type(of: self))
let nib = UINib(nibName: String(describing: type(of: self)), bundle: bundle)
let view = nib.instantiate(withOwner: self, options: nil)[0] as! UIView
return view
}
}
Add this class as superclass view in storyboard.

Custom UIView for an UIViewController in Swift

I use code to create the view (with subviews) for UIViewController's this is how I do it:
override loadView()
class MYViewController: UIViewController {
var myView: MyView! { return self.view as MyView }
override func loadView() {
view = MyView()
}
}
and here is how I create my custom view:
class MyView: UIView {
// MARK: Initialization
override init (frame : CGRect) {
super.init(frame : frame)
addSubviews()
setupLayout()
}
convenience init () {
self.init(frame:CGRect.zero)
}
required init(coder aDecoder: NSCoder) {
fatalError("This class does not support NSCoding")
}
// MARK: Build View hierarchy
func addSubviews(){
// add subviews
}
func setupLayout(){
// Autolayout
}
// lazy load views
}
I do this for all my View Controllers and I am looking for more elegant way, because this process is repetitive, so is there any solution for make that generic for example, create a super abstract class, or create an extension for UIViewController and UIView, Protocols ? I am new for swift and I think that Swift can have a better elegant solution with it's modern patterns
If you are wanting to create many different controllers with custom view classes my recommended solution would be along these lines:
First implement a custom view subclass the way you want to be able to use it, here I have used the one you had in your question. You can then subclass this anywhere you need it and just override the relevant methods.
class CustomView: UIView {
// MARK: Initialization
override init(frame: CGRect) {
super.init(frame: frame)
addSubviews()
setupLayout()
}
required init() {
super.init(frame: .zero)
addSubviews()
setupLayout()
}
required init(coder aDecoder: NSCoder) {
fatalError("This class does not support NSCoding")
}
// MARK: Build View hierarchy
func addSubviews(){
// add subviews
}
func setupLayout(){
// Autolayout
}
}
Then create a generic custom view controller that allows specification of a class as a generic parameter so that you can easily create a controller with a custom view class.
class CustomViewController<T: CustomView>: UIViewController {
var customView: T! { return view as! T }
override func loadView() {
view = T()
}
init() {
super.init(nibName: nil, bundle: nil)
}
}
Then if you wanted to define a new custom view and create a controller that uses it you can simply:
class AnotherCustomView: CustomView { /* Override methods */ }
...
let controller = CustomViewController<AnotherCustomView>()
Boom!
If you wanted you could even typealias this new controller type to make it even more elegant:
class AnotherCustomView: CustomView { /* Override methods */ }
...
typealias AnotherCustomViewController = CustomViewController<AnotherCustomView>
let controller = AnotherCustomViewController()

Is it possible to use IBDesignable with UICollectionViewCells and live render them in storyboard?

I know how to use #IBDesignable with custom views.
but is it possible to use IBDesignable for cells and render them in storyboard?
for example: i have a collectionViewController in storyboard, and added a uiCollectionCell and specified class as my customCellClass.
p.s: i know for using Xibs in collecionViews and tableViews we have to call method registerNib:forReuseIdentifer in code (and i am doing it). just wondered, is it possible to see it's rendered view in storyboard or not.
p.s2: i found this and it works perfectly with UIViews, but don't know how to make it work with CollectionCells and TableCells. :(
Yes. Here is what I found with Xcode 10.1 and iOS 12. Adding #IBDesignable to the custom subclass of UICollectionViewCell did work intermittently, but this works more reliably:
Add #IBDesignable to a custom subclass of UIView
Override layoutSubviews(), and define the appearance there
Optionally, if you want to define dummy data for IB only, override prepareForInterfaceBuilder()
Add that custom view to your prototype UICollectionViewCell in Interface Builder
You should see Interface Builder "build" the views and draw your change in your customer view (I find this unreliable, too. If nothing happens and Menu / Editor / Automatically Refresh Views is checked, make some other change in Interface Builder)
Example Class
#IBDesignable
class Avatar: UIView {
// Despite not being used for views designed in Interface Builder, must still be defined for custom UIView subclasses with #IBDesignable, or IB will report errors
override init(frame: CGRect) {
super.init(frame: frame)
}
// Used when a view is designed inside a view controller scene in Interface Builder and assigned to this custom UIView subclass
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override func layoutSubviews() {
super.layoutSubviews()
self.layer.cornerRadius = self.bounds.width / 2
self.backgroundColor = UIColor.gray
}
override func prepareForInterfaceBuilder() {
super.prepareForInterfaceBuilder()
self.backgroundColor = UIColor.blue
}
}
Yep. Here's how I did it.
First make sure the File Owner of NIB file is set to your custom cell class. Check this
Override the prepareForInterfaceBuilder method and add the contentView from NIB file in the contentView of prototype cell. This is what it looks like.
// ArticleTableViewCell.swift
import UIKit
#IBDesignable
class ArticleTableViewCell: UITableViewCell {
#IBOutlet weak var authorLabel: UILabel!
#IBOutlet weak var authorImage: UIImageView!
#IBOutlet weak var titleLabel: UILabel!
#IBOutlet weak var dateCreatedLabel: UILabel!
override func prepareForInterfaceBuilder() {
super.prepareForInterfaceBuilder()
addNIBContentView(toView: contentView)
}
private func addNIBContentView() {
let view = loadContentViewFromNib()
view.frame = bounds
view.autoresizingMask = [.flexibleWidth, .flexibleHeight]
contentView.addSubview(view)
}
private func loadContentViewFromNib() -> UIView {
let bundle = Bundle(for: type(of: self))
// Make sure your NIB file is named the same as this class, or else
// Put the name of NIB file manually (without the file extension)
let nib = UINib(nibName: String(describing: type(of: self)), bundle: bundle)
let view = nib.instantiate(withOwner: self, options: nil).first as! UIView
return view
}
}
Now set the custom class of the prototype cell in your table view to the one above and refresh the views.
Editor > Refresh All Views
If it still does not show up. Just clear the build folder and refresh all views again.
Product > Clean Build Folder
I made a handy extension for myself to reuse the last 2 functions in all UITableViews/UICollectionViews
// ViewExtensions.swift
import UIKit
extension UIView {
func addNIBContentView(toView contentView: UIView? = nil) {
let view = loadContentViewFromNib()
// Use bounds not frame or it'll be offset
view.frame = bounds
// Make the view stretch with containing view
view.autoresizingMask = [.flexibleWidth, .flexibleHeight]
if let contentView = contentView {
contentView.addSubview(view)
} else {
addSubview(view)
}
}
private func loadContentViewFromNib() -> UIView {
let bundle = Bundle(for: type(of: self))
// Make sure your NIB file is named the same as it's class
let nib = UINib(nibName: String(describing: type(of: self)), bundle: bundle)
let view = nib.instantiate(withOwner: self, options: nil).first as! UIView
return view
}
}
// ArticleTableViewCell.swift
import UIKit
#IBDesignable
class ArticleTableViewCell: UITableViewCell {
#IBOutlet weak var authorLabel: UILabel!
#IBOutlet weak var authorImage: UIImageView!
#IBOutlet weak var titleLabel: UILabel!
#IBOutlet weak var dateCreatedLabel: UILabel!
override func prepareForInterfaceBuilder() {
super.prepareForInterfaceBuilder()
addNIBContentView(toView: contentView)
}
}
After lots of testing and working with the library I came up with this:
you should not add TableViewCell or CollectionViewCells inside .nib files, instead you have to add simple View. I'm not sure if it's gonna show up inside storyboard or not (haven't checked it yet) but it makes errors go away. Now you can even use autoLayout for self sizing cells.

Resources