I have seen the other question, Swift - Segmented control - Switch multiple views, which would work if I had the segment control in the view. However, I have a segment control created programmatically in my viewDidLoad function and that segment control is set as the titleView for the navigation bar. It will not let me reference that segment control since it isn't in the nib file. I also tried the whole string of referencing it by self.navigationController?.navigationBar.topItem?.titleView.customSC.selectedSegmentIndex but that didn't work either.
Code:
class MyVC: UIViewController {
var webviewURL: NSURL = NSURL(string: "myURL")!
var webviewURL2: NSURL = NSURL(string: "myURL")!
var webviewURL3: NSURL = NSURL(string: "myURL")!
var webviewURL4: NSURL = NSURL(string: "myURL")!
@IBOutlet weak var webView: UIWebView!
@IBAction func indexChanged(sender: UISegmentedControl) {
switch customSC.selectedSegmentIndex { //error here
case 0:
let requestObj = NSURLRequest(URL: webviewURL)
webView.loadRequest(requestObj)
case 1:
let requestObj = NSURLRequest(URL: webviewURL2)
webView.loadRequest(requestObj)
case 2:
let requestObj = NSURLRequest(URL: webviewURL3)
webView.loadRequest(requestObj)
case 3:
let requestObj = NSURLRequest(URL: webviewURL4)
webView.loadRequest(requestObj)
default:
break;
}
}
override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) {
super.init(nibName: "myVC", bundle: nil)
}
convenience init() {
self.init(nibName: "myVC", bundle: nil)
//set the tab bar item's title
tabBarItem.title = "title"
//put an image on the tab bar item
tabBarItem.image = UIImage(named: "image")
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
let logo = UIImage(named: "image")
let logoView = UIImageView(frame: CGRect(x: 0, y: 0, width: 100, height: 80))
logoView.contentMode = .ScaleAspectFit
logoView.image = logo
let leftLogo = UIBarButtonItem(customView: logoView)
self.navigationItem.leftBarButtonItem = leftLogo
let items = ["Tab 1", "Tab 2", "Tab 3", "Tab 4"]
let customSC = UISegmentedControl(items: items)
customSC.selectedSegmentIndex = 0
navigationController?.navigationBar.topItem?.titleView = customSC
navigationController?.navigationBar.translucent = false
let requestObj = NSURLRequest(URL: webviewURL)
webView.loadRequest(requestObj)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}