I try to pass imageName string data from ViewController to ImageViewController
which also func sliderImageTapped is sending data to CPImageSlider class
// ViewController.swift
import UIKit
let _AUTO_SCROLL_ENABLED : Bool = false
class ViewController: UIViewController, CPSliderDelegate {
var imagesArray = [String]()
var passDataDelegate: PassImageName?
#IBOutlet weak var slider : CPImageSlider!
#IBOutlet weak var autoSwitch : UISwitch!
#IBOutlet weak var arrowSwitch : UISwitch!
#IBOutlet weak var indicatorSwitch : UISwitch!
#IBOutlet weak var sliderSwitch : UISwitch!
#IBOutlet weak var circularSwitch : UISwitch!
override func viewDidLoad() {
super.viewDidLoad()
imagesArray = ["wallpaper1.jpg","wallpaper2.jpg","wallpaper3.jpg","wallpaper4.jpg"]
slider.images = imagesArray
slider.delegate = self
let zoom : CGFloat = 0.8
autoSwitch.transform = CGAffineTransform(scaleX: zoom, y: zoom)
arrowSwitch.transform = CGAffineTransform(scaleX: zoom, y: zoom)
indicatorSwitch.transform = CGAffineTransform(scaleX: zoom, y: zoom)
sliderSwitch.transform = CGAffineTransform(scaleX: zoom, y: zoom)
circularSwitch.transform = CGAffineTransform(scaleX: zoom, y: zoom)
autoSwitch.isOn = slider.autoSrcollEnabled
arrowSwitch.isOn = slider.enableArrowIndicator
indicatorSwitch.isOn = slider.enablePageIndicator
sliderSwitch.isOn = slider.enableSwipe
circularSwitch.isOn = slider.allowCircular
}
func sliderImageTapped(slider: CPImageSlider, imageName: String, index: Int) {
passDataDelegate?.passData(clickedImageName: imageName)
guard let destinationVC = storyboard?.instantiateViewController(withIdentifier: "ImageViewController") as? ImageViewController else {
return
}
present(destinationVC, animated: true, completion: nil )
print("\(index)")
}
}
// ImageViewController.swift
import UIKit
protocol PassImageName {
func passData(clickedImageName:String)
}
class ImageViewController: UIViewController, PassImageName {
#IBOutlet weak var image: UIImageView!
var imageName:String?
func passData(clickedImageName: String) {
imageName = clickedImageName
}
override func viewDidLoad() {
super.viewDidLoad()
image.image = UIImage(named: imageName ?? "wallpaper1.jpg")
}
#IBAction func dismiss(_ sender: UIButton) {
dismiss(animated: true, completion: nil)
}
}
You must initialize passDataDelegate before call the delegate method.
func sliderImageTapped(slider: CPImageSlider, imageName: String, index: Int) {
guard let destinationVC = storyboard?.instantiateViewController(withIdentifier: "ImageViewController") as? ImageViewController else {
return
}
passDataDelegate = destinationVC
passDataDelegate?.passData(clickedImageName: imageName)
present(destinationVC, animated: true, completion: nil )
print("\(index)")
}
I don't understand the point of your delegate, is there something preventing you to just set the imageName after instantiating the ImageViewController ?
func sliderImageTapped(slider: CPImageSlider, imageName: String, index: Int) {
guard let destinationVC = storyboard?.instantiateViewController(withIdentifier: "ImageViewController") as? ImageViewController else {
return
}
destinationVC.imageName = imageName
present(destinationVC, animated: true, completion: nil )
print("\(index)")
}
And then just set your image inside it :
var imageName:String? {
didSet {
image.image = UIImage(named: imageName ?? "wallpaper1.jpg")
}
}
Related
When the image in the view I created with xib is clicked, I want it to go to the view controller in the storyboard. I tried segue-present and pushviewcontroller() but how can I do it?
Also, the delegate nil in the imageClicked() function is coming.delagate should not be nil
This is xib file:
xib view
import UIKit
protocol BookDetailVideoViewDelegate : class {
func videoOpen(value: Bool)
}
class BookDetailVideoViewController: UIViewController{
weak var delegate : BookDetailVideoViewDelegate?
var book : Book?
var videoUrl = ""
var url: URL?
var index = 0
#IBOutlet weak var bookImageView: UIImageView!
//var book = self.book
#IBOutlet weak var bookImageViewWidthConstraint: NSLayoutConstraint!
override func viewDidLoad() {
super.viewDidLoad()
if #available(iOS 11.0, *) {
self.extendedLayoutIncludesOpaqueBars = true
} else {
self.edgesForExtendedLayout = []
}
self.navigationController?.navigationBar.isTranslucent = false
//self.bookImageViewWidthConstraint.constant = UIScreen.main.bounds.width * 0.35
self.view.layoutIfNeeded()
if let url = self.url {
self.bookImageView.kf.setImage(with: url)
}
self.bookImageView.layer.cornerRadius = 10
bookImageView.isUserInteractionEnabled = true
let gestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(imageClicked))
bookImageView.addGestureRecognizer(gestureRecognizer)
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
}
deinit {
self.url = nil
}
#objc func imageClicked(){
print(delegate as Any)
self.delegate?.videoOpen(value: true)
}
func initializeView(url: URL, index: Int , book: Book) {
self.index = index
self.url = url
self.book = book
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
}
}
The view controller is like this:
import UIKit
import YoutubePlayer_in_WKWebView
class YoutubeVideoViewController: UIViewController , BookDetailVideoViewDelegate, WKYTPlayerViewDelegate {
let myDelegate : BookDetailVideoViewController = BookDetailVideoViewController()
var boolvalue = true
var book : Book?
#IBOutlet weak var playerView: WKYTPlayerView!
override func viewDidLoad() {
super.viewDidLoad()
playerView.delegate = self
myDelegate.delegate = self
let mediakey = book!.mediaKey as String?
playerView.load(withVideoId: mediakey!)
}
func videoOpen(value : Bool) {
guard let ViewC = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "YoutubeVideoViewController") as? YoutubeVideoViewController else{return}
ViewC.book = book
ViewC.boolvalue = value
self.present(ViewC, animated: true)
}
}
I am working on an app in which i am using UITableviewCell to display feed data. In Cell i am using multiple UIButtons to perform actions.
The main issue arise when i perform action through buttons the method is not called for the very first time(TableViewCell content is not updated). But when i press button second time it works fine.
Here is my code
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
{
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell_Reels", for: indexPath) as! Cell_Reels
cell.delegate = self
DispatchQueue.main.asyncAfter(deadline: .now()+0.1) { [self] in
UIView.animate(withDuration: 12.0, delay: 1, options: ([.curveLinear, .repeat]), animations: {() -> Void in
cell.marqueeLabel.center = CGPoint.init(x: 35 - cell.marqueeLabel.bounds.size.width / 2, y: cell.marqueeLabel.center.y)
}, completion: { _ in })
cell.likebutton.tag = indexPath.row
cell.FollowButton.tag = indexPath.row
cell.shareBtn.tag = indexPath.row
cell.shareBtn.addTarget(self, action: #selector(buttonShare), for: .touchUpInside)
let VideoStr = self.videos[indexPath.row]["media"].string ?? ""
self.fullVideoUrl = "\(KeyConstant.KBaseImageURL)\(VideoStr)"
//print("======", self.fullVideoUrl)
cell.configureCell( videoUrl: self.fullVideoUrl)
self.pausePlayeVideos()
cell.totalViews.text = "\(self.videos[indexPath.row]["count_view"].string ?? "") Views"
cell.nameLbl.text = self.videos[indexPath.row]["full_name"].string ?? ""
cell.descLbl.text = self.videos[indexPath.row]["title"].string ?? ""
cell.marqueeLabel.text = self.videos[indexPath.row]["title"].string ?? ""
cell.idLbl.text = self.videos[indexPath.row]["id"].string ?? ""
cell.likedLbl.text = self.videos[indexPath.row]["like_status"].string ?? ""
cell.followedLbl.text = self.videos[indexPath.row]["follow_status"].string ?? ""
self.currentLikesStr = self.videos[indexPath.row]["count_like"].string ?? ""
cell.likesCountLabel.text = "\(self.currentLikesStr) Likes"
self.followedStr = self.videos[indexPath.row]["follow_status"].string ?? ""
print("followedStr ppppppppppppppppppppppppp",followedStr, cell.idLbl.text!)
if self.followedStr == "0"
{
cell.FollowButton .setTitle("Follow", for: UIControl.State.normal)
}
else
{
cell.FollowButton .setTitle("Following", for: UIControl.State.normal)
}
self.likedStr = self.videos[indexPath.row]["like_status"].string ?? ""
print("likedStr -=-==-===-=-=-",likedStr, cell.idLbl.text!)
if likedStr == "0"
{
let selectedImage = UIImage(named: "heart_y2_30x30") as UIImage?
cell.likebutton.setImage(selectedImage, for: UIControl.State.normal)
}
else
{
let selectedImage = UIImage(named: "heart_y_30x30") as UIImage?
cell.likebutton.setImage(selectedImage, for: UIControl.State.normal)
}
cell.CommentsCountLabel.text = "Comments"
}
return cell
}
Button method decleration
func addFollowed(cell: Cell_Reels)
{
followedStr = cell.followedLbl.text!
let idstr = cell.idLbl.text
print(userId, idstr ?? "", followedStr)
let VideoidStr = cell.idLbl.text
print("=====", VideoidStr!)
let deviceid = "12345"
//print(videoId)
WebServiceHelper.sharedInstanceAPI.hitPostAPI(urlString: KeyConstant.APIFollow, params: ["user_id":userId, "device_id": deviceid, "device_type" : "iOS", "video_id":VideoidStr!], completionHandler: { (result: [String:Any], err:Error?) in
//print(result)
DispatchQueue.main.async {
//MBProgress().hideIndicator(view: self.view)
}
if(!(err == nil))
{
return
}
let json = JSON(result)
let statusCode = json["status"].string
//print(json)
if(statusCode == "success")
{
DispatchQueue.main.asyncAfter(deadline: .now()+0.1) { [self] in
self.followedStr = json["follow_status"].string ?? ""
cell.followedLbl.text = "\(self.followedStr)"
print(self.followedStr)
print(";;;;;;;;;;;;;;;;;;", self.followedStr)
if self.followedStr == "0"
{
cell.FollowButton .setTitle("Follow", for: UIControl.State.normal)
self.followedStr = "1"
self.arrayTempData[cell.FollowButton.tag] = 1
}
else
{
cell.FollowButton .setTitle("Following", for: UIControl.State.normal)
self.followedStr = "0"
self.arrayTempData[cell.FollowButton.tag] = 0
}
}
}
})
self.tblInstaReels.reloadData()
self.followedStr = ""
}
This i defined in TableViewCell class
protocol TableViewCellDelegate
{
func addTapped(cell: Cell_Reels, Tlikes : String)
func addFollowed(cell: Cell_Reels)
}
class Cell_Reels: UITableViewCell, ASAutoPlayVideoLayerContainer
{
var delegate: TableViewCellDelegate?
#IBOutlet weak var likedLbl : UILabel!
#IBOutlet weak var followedLbl : UILabel!
#IBOutlet weak var idLbl : UILabel!
#IBOutlet weak var nameLbl : UILabel!
#IBOutlet weak var likesCountLabel : UILabel!
#IBOutlet weak var CommentsCountLabel : UILabel!
#IBOutlet weak var marqueeLabel: UILabel!
#IBOutlet weak var imgReels: UIImageView!
#IBOutlet weak var Bkview: UIView!
#IBOutlet weak var PauseBtn: UIButton!
#IBOutlet weak var descLbl: UILabel!
#IBOutlet weak var shareBtn : UIButton!
#IBOutlet weak var likebutton : UIButton!
#IBOutlet weak var FollowButton : UIButton!
#IBOutlet weak var totalViews : UILabel!
var playerController: ASVideoPlayerController?
var videoLayer: AVPlayerLayer = AVPlayerLayer()
var likestr = ""
private(set) var liked = false
private(set) var followed = false
var VideoId = ""
#IBAction func followed(_ sender: Any)
{
delegate?.addFollowed(cell: self)
}
#IBAction func like(_ sender: Any)
{
delegate?.addTapped(cell: self, Tlikes: self.likedLbl.text!)
}
func likeVideo()
{
print("==========", likestr)
}
var videoURL: String?
{
didSet {
if let videoURL = videoURL
{
ASVideoPlayerController.sharedVideoPlayer.setupVideoFor(url: videoURL)
}
videoLayer.isHidden = videoURL == nil
}
}
override func awakeFromNib()
{
super.awakeFromNib()
imgReels.layer.addSublayer(videoLayer)
selectionStyle = .none
}
func configureCell(videoUrl: String?)
{
self.videoURL = videoUrl
}
override func prepareForReuse()
{
imgReels.imageURL = nil
super.prepareForReuse()
}
override func layoutSubviews()
{
super.layoutSubviews()
let horizontalMargin: CGFloat = 20
let width: CGFloat = bounds.size.width - horizontalMargin * 2
let height: CGFloat = (width * 0.9).rounded(.up)
videoLayer.frame = CGRect(x: 0, y: 0, width: imgReels.layer.frame.width, height: imgReels.layer.frame.height)
}
func visibleVideoHeight() -> CGFloat
{
return imgReels.frame.size.height
let videoFrameInParentSuperView: CGRect? = self.superview?.superview?.convert(imgReels.frame, from: imgReels)
guard let videoFrame = videoFrameInParentSuperView,
let superViewFrame = imgReels?.frame else {
return 0
}
let visibleVideoFrame = videoFrame.intersection(superViewFrame)
return visibleVideoFrame.size.height
}
}
in place of calling a separate method, use the addTarget method.
if you update anything in table view then perform all operations in cellForRowAt else after scrolling it reused the cell and it will create ambiguity
reload the table view in the main thread.
Hi everyOne actually I want to add Data of the cell in tableView that when I click on it , data should pass on showOfferController(another view controller) but I dont why my data is nil when passed on showOfferController:
this is my prepareForSegue function :
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "cellToShow" {
let prePag = segue.destination as! ShowOfferController
//print("title : \(title)")
if WelcomeJson.CodingKeys.title.rawValue == titleItem {
prePag.celanderItem = WelcomeJson.CodingKeys.dateOfExpire.rawValue
prePag.itemImage[0] = imageString
prePag.itemAddress = WelcomeJson.CodingKeys.address.rawValue
prePag.itemOffer = WelcomeJson.CodingKeys.offer.rawValue
prePag.itemDefine = WelcomeJson.CodingKeys.about.rawValue
}
}
}
And also this is my DidSelectRow TableView function :
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
performSegue(withIdentifier: "cellToShow", sender: nil)
}
this is my ShowOfferController on main.storyBoard and also my viewController or VC1 that tabelViewCell point to ShowOfferController:
And here my ShowOfferController.swift code :
class ShowOfferController: UIViewController, UIScrollViewDelegate {
#IBOutlet weak var offerScroll: UIScrollView!
#IBOutlet weak var offerPageController: UIPageControl!
#IBOutlet weak var getLabel: UILabel!
#IBOutlet weak var percentLbl: UILabel!
#IBOutlet weak var calendar: UILabel!
#IBOutlet weak var address: UILabel!
let locations = NSTextAttachment()
let calendars = NSTextAttachment()
let precents = NSTextAttachment()
var itemAddress : String = ""
var itemOffer : String = ""
var celanderItem : String = ""
var itemImage : [String] = []
var itemDefine : String = ""
var frame: CGRect = CGRect(x:0, y:0, width:0, height:0)
override func viewDidLoad() {
super.viewDidLoad()
print("item of images is : \(itemImage)")
// Do any additional setup after loading the view.
offerPageController.numberOfPages = itemImage.count
setupImages()
offerScroll.delegate = self
getLabel.text = itemDefine
locations.image = UIImage(systemName: "location.fill")
let locationVaAdress = NSMutableAttributedString(string: ". ")
locationVaAdress.append(NSAttributedString(attachment: locations))
locationVaAdress.append(NSAttributedString(string: " \(itemAddress)"))
address.attributedText = locationVaAdress
calendars.image = UIImage(systemName: "calendar")
let calendarss = NSMutableAttributedString(string: ". ")
calendarss.append(NSAttributedString(attachment: calendars))
calendarss.append(NSAttributedString(string: " \(celanderItem)"))
calendar.attributedText = calendarss
precents.image = UIImage(systemName: "percent")
let percentAndDarsad = NSMutableAttributedString(string: ". ")
percentAndDarsad.append(NSAttributedString(attachment: precents))
percentAndDarsad.append(NSAttributedString(string: " \(itemOffer)"))
percentLbl.attributedText = percentAndDarsad
}
func setupImages() {
for index in 0..<itemImage.count {
// 1.
frame.origin.x = offerScroll.frame.size.width * CGFloat(index)
frame.size = offerScroll.frame.size
let correctScope = itemImage[index].addingPercentEncoding(withAllowedCharacters: .urlPathAllowed)
let unoptionalScope = correctScope!
let imgUrl = URL(string: "http://5.63.13.16:8080/\(unoptionalScope)")!
if let data = try? Data(contentsOf: imgUrl) {
let imgOffer = UIImageView(frame: frame)
imgOffer.image = UIImage(data: data)
self.offerScroll.addSubview(imgOffer)
}
offerScroll.contentSize = CGSize(width: (offerScroll.frame.size.width * CGFloat(itemImage.count)), height: offerScroll.frame.size.height)
offerScroll.delegate = self
}
}
func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
let pageNumber = offerScroll.contentOffset.x / offerScroll.frame.size.width
offerPageController.currentPage = Int(pageNumber)
}
so what's your idea ?
You should make (drag) the segue from on top of the table view controller in the storyboard instead of from the row
The image is not from one VC to another VC.
The problem is displaying it to the image view in the main UIViewController. I have everything hooked up correctly in the Storyboard.
Click here to view my storyboard layout.
Please note some of my unnecessary code has been removed from both ViewController classes.
Here is my first UIViewController:
import UIKit
class ViewController: UIViewController, UINavigationControllerDelegate, UIImagePickerControllerDelegate {
var imagePicker: UIImagePickerController!
#IBAction func editPhoto(_ sender: UIButton) {
let ViewController2 = storyboard?.instantiateViewController(withIdentifier: "AddNewEaterySegue") as! ViewController2
ViewController2.imageForEdit = imageView.image!
print(imageView)
print(imageView.image!)
navigationController?.pushViewController(ViewController2, animated: true)
}
#IBOutlet weak var imageView: UIImageView! {
didSet {
imageView.contentMode = .scaleAspectFill
imageView.clipsToBounds = true
}
}
}
Here is my second UIViewController:
import UIKit
class ViewController2: UIViewController, UINavigationControllerDelegate, UIImagePickerControllerDelegate {
var filter : CIFilter!
var imageForEdit = UIImage()
var imagePicker: UIImagePickerController!
#IBOutlet weak var select: UISegmentedControl!
#IBOutlet weak var imageLabel: UIImageView!
#IBOutlet weak var textField: UITextField!
#IBAction func saveButtonPressed(_ sender: UIImage) {
if textField.text == "" {
print("Не все поля заполнены")
} else {
}
performSegue(withIdentifier: "unwindSegueFromViewController", sender: sender)
}
override func viewDidLoad() {
super.viewDidLoad()
imageLabel.image = imageForEdit
print(imageLabel)
// Do any additional setup after loading the view.
}
#IBAction func tappedEnter(_ sender: Any) {
if textField.text?.isEmpty ?? true {
return
} else {
if let texttxt = textField.text {
let data = texttxt.data(using: .ascii, allowLossyConversion: false)
if select.selectedSegmentIndex == 0
{
filter = CIFilter(name: "CICode128BarcodeGenerator")
} else {
filter = CIFilter(name: "CIQRCodeGenerator")
}
filter.setValue(data, forKey: "inputMessage")
let transform = CGAffineTransform(scaleX: 5, y: 5)
let image = UIImage(ciImage: filter.outputImage!.transformed(by: transform))
imageLabel.image = image
}
}
}
}
When you are pushing to ViewController2 your imageView in ViewController is empty.
Where exactly are you setting the image for imageView?
In your storyboard, the imageView in ViewController is empty and also in the didSet method for imageView in ViewController you have not set any image to the imageView.
Try this in ViewController:
#IBOutlet weak var imageView: UIImageView! {
didSet {
//Add a test image to your project.
imageView.image = UIImage(named: "YOUR_TEST_IMAGE_NAME.jpeg")
imageView.contentMode = .scaleAspectFill
imageView.clipsToBounds = true
}
}
EDIT: Ok I guess I was not clear on your question. So in order to send the image from "ViewController2" back to "ViewController", you can use many methods but the way I would do it is by using Protocols.
I have done it in a generic way but you can apply this to send any kind of data from one view controller back to the previous view controller.
Try this in ViewController:
import UIKit
protocol ImageViewProtocol{
func sendImageToViewController(theImage: UIImage)
}
class ViewController: UIViewController, ImageViewProtocol {
func sendImageToViewController(theImage: UIImage) {
imageView.image = theImage
}
#IBOutlet weak var imageView: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
let viewcontroller2 = storyboard?.instantiateViewController(withIdentifier: "viewcontroller2") as! ViewController2
viewcontroller2.delegate = self
self.navigationController?.pushViewController(viewcontroller2, animated: true)
}
}
Try this in ViewController2:
import UIKit
class ViewController2: UIViewController {
var delegate: ImageViewProtocol!
#IBOutlet weak var barcodeImageView: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
barcodeImageView.image = UIImage(named: "test_image.jpg")
}
#IBAction func saveButtonAction(_ sender: Any) {
delegate.sendImageToViewController(theImage: barcodeImageView.image!)
self.navigationController?.popViewController(animated: true)
}
}
I am loading a views from nib and i am successfully loaded but first one is loaded perfect but in second view getting nil outlets. below is my code.
Set a global variable to loadview by default is is 0 and it is increase when i press next button.
User is struct here :
struct User {
static var quizIndexNo = 0
}
This method is in my ViewController
let moptViewInstance = MOPT()
let rmkViewInstance = RMK()
getting view name from this array:
let viewName = ["MOPT","RMK"]
func loadQuizView(){
if viewName[User.quizIndexNo] == "MOPT" {
for views in vwOptionView.subviews {
views.removeFromSuperview()
}
moptViewInstance.prepareScreenWithView(navigationController: UINavigationController(), viewSize: self.vwOptionView, viewController: self)
} else if viewName[User.quizIndexNo] == "RMK" {
for views in vwOptionView.subviews {
views.removeFromSuperview()
}
rmkViewInstance.prepareScreenWithView(navigationController: UINavigationController(), viewSize: self.vwOptionView, viewController: self)
}
}
// NIB View Classes
class MOPT: UIView {
#IBOutlet weak var btnPrevious: UIButton!
#IBOutlet weak var btnNext: UIButton!
var nibView: UIView!
var instanceOfQuizController : QuizCointroller!
func prepareScreenWithView(navigationController: UINavigationController, viewSize: UIView, viewController: UIViewController) {
nibView = Bundle.main.loadNibNamed("MOPT", owner: self, options: nil)?[0] as! UIView
nibView.tag = 200
var tempRect = nibView.frame
print(tempRect)
if User.quizIndexNo == 0 {
btnPrevious.isHidden = true
}
if User.quizIndexNo == 0 {
btnNext.setTitle("Test", for: .normal)
}
print("Index No is: \(User.quizIndexNo) and \(Sequence.totalQuizQuestionCout)")
if User.quizIndexNo == Sequence.totalQuizQuestionCout - 1 {
btnNext.setTitle("Submit", for: .normal)
}
instanceOfQuizController = viewController as! QuizCointroller
tempRect = CGRect(x: 0, y: 0, width: viewSize.bounds.width, height: viewSize.bounds.height)
viewSize.addSubview(self.nibView)
self.nibView.frame = tempRect
}
#IBAction func btnPrev(_ sender: UIButton) {
User.quizIndexNo -= 1
Sequence.instanceOfQuizControllerTest.previousButtonPressed()
}
// Next button will reload next view
#IBAction func btnNext(_ sender: UIButton) {
User.quizIndexNo += 1
// here sequence is global variable of type ViewController
Sequence.instanceOfQuizControllerTest.nextButtonPressed()
}
}
Second NibView Class
class RMK: UIView {
#IBOutlet weak var btnPrevious: UIButton!
#IBOutlet weak var btnNext: UIButton!
var nibView: UIView!
var instanceOfQuizControllerTest : QuizCointroller!
func prepareScreenWithView(navigationController: UINavigationController, viewSize: UIView, viewController: UIViewController) {
nibView = Bundle.main.loadNibNamed("RMK", owner: self, options: nil)?[0] as! UIView
nibView.tag = 200
var tempRect = nibView.frame
print(tempRect)
if User.quizIndexNo == 1 {
btnPrevious.isHidden = true //app is crashing here when i am trying to set title Button is showing nil
}
if User.quizIndexNo == 1 {
btnNext.setTitle("Submit", for: .normal)
}
instanceOfQuizControllerTest = viewController as! QuizCointroller
print("Quiz ViewController instatnce \(instanceOfQuizControllerTest)")
tempRect = CGRect(x: 0, y: 0, width: viewSize.bounds.width, height: viewSize.bounds.height)
viewSize.addSubview(self.nibView)
self.nibView.frame = tempRect
}
#IBAction func btnPrev(_ sender: UIButton) {
User.quizIndexNo -= 1
Sequence.instanceOfQuizControllerTest.previousButtonPressed()
}
#IBAction func btnNext(_ sender: UIButton) {
print(instanceOfQuizControllerTest)
User.quizIndexNo += 1
Sequence.instanceOfQuizControllerTest.nextButtonPressed()
}
}