I'm working on a project that has a custom segmented control in a UIScrollView. I want to use auto layout to position the segmented control. I'm using this project as my model: https://github.com/honghaoz/UIScrollView-and-AutoLayout
import UIKit
class ViewController: UIViewController {
let scrollView = UIScrollView()
var screenBounds: CGRect { return UIScreen.main.bounds }
override var preferredStatusBarStyle : UIStatusBarStyle {
return .lightContent
}
override func viewDidLoad() {
super.viewDidLoad()
// Setup scroll view
scrollView.translatesAutoresizingMaskIntoConstraints = false
scrollView.backgroundColor = UIColor(red:20/255.0, green:119/255.0, blue:61/255.0, alpha:255/255.0)
view.addSubview(scrollView)
// Setup constraints
var views: [String: UIView] = [
"scrollView": scrollView
]
var constraints = [NSLayoutConstraint]()
// External constraints
constraints += NSLayoutConstraint.constraints(withVisualFormat: "H:|[scrollView]|", options: [], metrics: nil, views: views)
constraints += NSLayoutConstraint.constraints(withVisualFormat: "V:|[scrollView]|", options: [], metrics: nil, views: views)
// Internal constraints
// Note: to let scrollView determines its contentSize, four edges should be explicitly specified
let v1 = newLabelWithText("v1 v1 v1 v1 v1 v1 v1 v1 v1 v1")
scrollView.addSubview(v1)
views["v1"] = v1
//Create Segmented Control
let segmentedB = YSSegmentedControl(
//Set Frame in Callback (Required)
frame: CGRect(x: 0, y: 0, width: 400, height: 60),
titles: [
"Yes",
"No"
],
action: {
control, index in
print ("segmented did pressed \(index)")
})
scrollView.addSubview(segmentedB)
views["v4"] = segmentedB
let v2 = newLabelWithText("v2 v2 v2 v2 v2")
views["v2"] = v2
let v3 = newLabelWithText("v3 v3 v3 v3 v3")
views["v3"] = v3
scrollView.addSubview(v3)
// Horizontal, fully specified
constraints += NSLayoutConstraint.constraints(withVisualFormat: "H:|-200-[v4]-300-|", options: .alignAllLastBaseline, metrics: nil, views: views)
// Vertically, fully specified
constraints += NSLayoutConstraint.constraints(withVisualFormat: "V:|-200-[v3]-1000-|", options: .alignAllLeading, metrics: nil, views: views)
NSLayoutConstraint.activate(constraints)
print("scrollView.contentSize: \(scrollView.contentSize)")
}
}
For some reason, auto layout works just fine with the text labels but not with the segmented control. The callback requires that I input parameters for CGRect, so I simply set the width and height and leave the position parameters at zero. This worked when there was no scrollview, but its not working now.
Also, I'm not using storyboards in this project. All constraints and views are created programmatically.
Any Help appreciated. Thanks
I think you should add this line before adding constraints
segmentedB.translatesAutoresizingMaskIntoConstraints = false
Whenever you add constraints programmatically you should set this property to false in order for constraints to take effect on the view
Related
I love using iCarousel in my swift projects but there is one thing that I could not manage to overcome; I want to use Visual language for layout of the views in my project but whenever I use visual formats for iCarousel, it does not work.
I noticed that the problem is TopMenuCarousel.translatesAutoresizingMaskIntoConstraints=false attribute.
Whenever I disable this attribute, my visual format constraints are disabled for iCarousel, and whenever I enable it, the constraints works perfectly but my iCarousel wont scroll and stay still always.
Current code:
#
import UIKit
import iCarousel
class Step2_HomePage: UIViewController,iCarouselDelegate,iCarouselDataSource {
let TopMenuCarouselCount = 5
var TopMenuCarousel = iCarousel()
override func viewDidLoad() {
super.viewDidLoad()
print("Step2HomePage icinde")
TopMenuCarousel = iCarousel(frame: CGRect())
view.addSubview(TopMenuCarousel)
// TopMenuCarousel.clipsToBounds = true
TopMenuCarousel.type = .Linear
TopMenuCarousel.dataSource = self
TopMenuCarousel.delegate = self
let views = [ "TopMenuCarousel": TopMenuCarousel ]
// 2
var allConstraints = [NSLayoutConstraint]()
let TopMenuCarouselTop = NSLayoutConstraint.constraintsWithVisualFormat(
"V:|-100-[TopMenuCarousel]",
options: [],
metrics: nil,
views: views)
allConstraints += TopMenuCarouselTop
let TopMenuCarouselHorizontal = NSLayoutConstraint.constraintsWithVisualFormat(
"H:|-0-[TopMenuCarousel]-0-|",
options: [],
metrics: nil,
views: views)
allConstraints += TopMenuCarouselHorizontal
TopMenuCarousel.translatesAutoresizingMaskIntoConstraints=false
NSLayoutConstraint.activateConstraints(allConstraints)
// Do any additional setup after loading the view, typically from a nib.
}
func numberOfItemsInCarousel(carousel: iCarousel) -> Int {
print("carousel number")
return TopMenuCarouselCount
}
func carousel(carousel: iCarousel, viewForItemAtIndex index: Int, reusingView view: UIView?) -> UIView {
print("carousel view icinde")
let tempView = UIView(frame: CGRect(x: 0, y: 0 , width: 20, height: 20))
tempView.backgroundColor = UIColor.blueColor()
return tempView
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
#
Looks like you're not setting any height to your iCarousel object. Try changing your first Constraint to:
let TopMenuCarouselTop = NSLayoutConstraint.constraintsWithVisualFormat(
"V:|-100-[TopMenuCarousel(20)]",
options: [],
metrics: nil,
views: views)
Here is a full modified version of your original code. I made the views larger (yours were 20x20), and added some color to make it easier to see what's going on.
import UIKit
import iCarousel
class Step2_HomePage: UIViewController,iCarouselDelegate,iCarouselDataSource {
// array of colors to make it easy to see the individual Carousel views
let arrayOfColors = [ UIColor.blueColor(), UIColor.redColor(), UIColor.yellowColor(), UIColor.orangeColor(), UIColor.greenColor()]
let TopMenuCarouselCount = 5
var TopMenuCarousel = iCarousel()
override func viewDidLoad() {
super.viewDidLoad()
print("Step2HomePage icinde")
self.view.backgroundColor = UIColor.lightGrayColor()
// initialize the TopMenuCarousel object
TopMenuCarousel = iCarousel(frame: CGRect())
// add TopMenuCarousel to the view
view.addSubview(TopMenuCarousel)
// if clipsToBounds == true, TopMenuCarousel subviews will be clipped to the TopMenuCarousel frame
// default is false
// TopMenuCarousel.clipsToBounds = true
TopMenuCarousel.type = .Linear
TopMenuCarousel.dataSource = self
TopMenuCarousel.delegate = self
TopMenuCarousel.backgroundColor = UIColor.purpleColor()
let views = [ "TopMenuCarousel": TopMenuCarousel ]
var allConstraints = [NSLayoutConstraint]()
// position TopMenuCarousel 100 from the Top, with a Height of 200
let TopMenuCarouselTop = NSLayoutConstraint.constraintsWithVisualFormat(
"V:|-100-[TopMenuCarousel(200)]",
options: [],
metrics: nil,
views: views)
allConstraints += TopMenuCarouselTop
// set TopMenuCarousel to stretch the full Width of the view
let TopMenuCarouselHorizontal = NSLayoutConstraint.constraintsWithVisualFormat(
"H:|-0-[TopMenuCarousel]-0-|",
options: [],
metrics: nil,
views: views)
allConstraints += TopMenuCarouselHorizontal
// this property *must* be set to false
TopMenuCarousel.translatesAutoresizingMaskIntoConstraints=false
NSLayoutConstraint.activateConstraints(allConstraints)
}
func numberOfItemsInCarousel(carousel: iCarousel) -> Int {
print("carousel number \(TopMenuCarouselCount)")
return TopMenuCarouselCount
}
func carousel(carousel: iCarousel, viewForItemAtIndex index: Int, reusingView view: UIView?) -> UIView {
print("carousel view icinde", index)
// create a 200 x 160 view to add to TopMenuCarousel
let tempView = UIView(frame: CGRect(x: 0, y: 0 , width: 200, height: 160))
// give it one of the colors
tempView.backgroundColor = arrayOfColors[index % arrayOfColors.count]
return tempView
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
The constraints are created and activated but never added to the view, you should use:
view.addConstraints(allConstraints)
after
NSLayoutConstraint.activateConstraints(allConstraints)
Also as DonMag stated, there is no height constraint, this means that if the iCarousel view doesn't have a correct intrinsic size it won't be displayed and you should add an explicit height like the example DonMag wrote.
I have a UIViewController with four UIButtons (2 x 2) on it that I laid out in interface builder that worked perfectly. I'm going to have a free and ad-supported version of my app, so I need to redo that scene to load based on whether the app is a paid or ad-supported version. Based on that, I'm attempting to use Visual Formatting Language to lay out the view. I'm getting incorrect values for my UIButton heights despite accounting for them when I calculate them. I can't figure out my mistake (or omission?).
Here's a screenshot of my interface builder.
I do not have constraints on my buttons in interface builder, but I do have IBOutlets wired to MyViewController. MyViewController is in a navigation controller and has a tab bar at the bottom.
I created a method called layoutButtons that I call in viewDidLoad just after super.viewDidLoad(). Here it is:
func layoutButtons() {
// Configure layout constraints
// Remove interface builder constraints from storyboard
view.removeConstraints(view.constraints)
// create array to dump constraints into
var allConstraints = [NSLayoutConstraint]()
// determine screen size
let screenSize: CGRect = UIScreen.mainScreen().bounds
let navBarRect = navigationController!.navigationBar.frame
let navBarHeight = navBarRect.height
let tabBarRect = tabBarController!.tabBar.frame
let tabBarHeight: CGFloat = tabBarRect.height
// calculate button width based on screen size
// padding for left + middle + right = 8.0 + 8.0 + 8.0 = 24.0
let buttonWidth = (screenSize.width - 24.0) / 2
/*
My buttons are extending under the top & bottom layout guides despite accounting
for them when I set the buttonHeight.
*/
// padding for top + middle + bottom = 8.0 + 8.0 + 8.0 = 24.0
let buttonHeight = (screenSize.height - topLayoutGuide.length - bottomLayoutGuide.length - 24.0) / 2
// create dictionary of metrics
let metrics = ["buttonWidth": buttonWidth,
"buttonHeight": buttonHeight,
"navBarHeight": navBarHeight,
"tabBarHeight": tabBarHeight,
"bannerAdWidth": bannerAdWidth,
"bannerAdHeight": bannerAdHeight]
// create dictionary of views
var views: [String : AnyObject] = ["firstButton": firstButton,
"secondButton": secondButton,
"thirdButton": thirdButton,
"fourthButton": fourthButton,
"topLayoutGuide": topLayoutGuide,
"bottomLayoutGuide": bottomLayoutGuide]
let topRowHorizontalConstraints = NSLayoutConstraint.constraintsWithVisualFormat(
"H:|-[firstButton(buttonWidth)]-[secondButton(buttonWidth)]-|",
options: [.AlignAllCenterY],
metrics: metrics,
views: views)
allConstraints += topRowHorizontalConstraints
let bottomRowHorizontalConstraints = NSLayoutConstraint.constraintsWithVisualFormat(
"H:|-[thirdButton(buttonWidth)]-[fourthButton(buttonWidth)]-|",
options: [.AlignAllCenterY],
metrics: metrics,
views: views)
allConstraints += bottomRowHorizontalConstraints
let leftColumnVerticalConstraints = NSLayoutConstraint.constraintsWithVisualFormat(
"V:|[topLayoutGuide]-[firstButton(buttonHeight)]-[thirdButton(buttonHeight)]-[bottomLayoutGuide]|",
options: [],
metrics: metrics,
views: views)
allConstraints += leftColumnVerticalConstraints
let rightColumnVerticalConstraints = NSLayoutConstraint.constraintsWithVisualFormat(
"V:|[topLayoutGuide]-[secondButton(buttonHeight)]-[fourthButton(buttonHeight)]-[bottomLayoutGuide]|",
options: [],
metrics: metrics,
views: views)
allConstraints += rightColumnVerticalConstraints
NSLayoutConstraint.activateConstraints(allConstraints)
}
I've fiddled with my buttonHeight variable, but every iteration I've tried results in the buttons extending under the topLayoutGuide and bottomLayoutGuide. Here's what it looks like at runtime:
I welcome any suggestions where to look for my mistake. Thank you for reading.
I originally followed a Ray Wenderlich's Visual Format Language tutorial and the tutorial's setup was similar to mine in that the subViews were on a storyboard and wired to MyViewController with IBOutlets.
Out of desperation, I nuked the storyboard and created the UIButtons in code. Along the way, I discovered my problem was I was setting the image on the button before it was laid out. The moral of the story is don't set images on UIButtons until they're laid out!
Below is the code called from a method in my viewDidLoad that lays out a 2 x 2 grid of buttons:
// Configure Buttons
firstButton.translatesAutoresizingMaskIntoConstraints = false
// code to customize button
secondButton.translatesAutoresizingMaskIntoConstraints = false
// code to customize button
thirdButton.translatesAutoresizingMaskIntoConstraints = false
// code to customize button
fourthButton.translatesAutoresizingMaskIntoConstraints = false
// code to customize button
// Add buttons to the subview
view.addSubview(firstButton)
view.addSubview(secondButton)
view.addSubview(thirdButton)
view.addSubview(fourthButton)
// create views dictionary
var allConstraints = [NSLayoutConstraint]()
let views: [String : AnyObject] = ["firstButton": firstButton,
"secondButton": secondButton,
"thirdButton": thirdButton,
"fourthButton": fourthButton,
"topLayoutGuide": topLayoutGuide,
"bottomLayoutGuide": bottomLayoutGuide]
// Calculate width and height of buttons
// 24.0 = left padding + middle padding + right padding
let buttonWidth = (screenSize.width - 24.0) / 2
let buttonHeight = (screenSize.height - topLayoutGuide.length - bottomLayoutGuide.length - 24.0) / 2
// Create a dictionary of metrics
let metrics = ["buttonWidth": buttonWidth,
"buttonHeight" : buttonHeight]
let topVerticalConstraints = NSLayoutConstraint.constraintsWithVisualFormat(
"V:|[topLayoutGuide]-[firstButton(buttonHeight)]",
options: [],
metrics: metrics,
views: views)
allConstraints += topVerticalConstraints
let topRowHorizontalConstraints = NSLayoutConstraint.constraintsWithVisualFormat(
"H:|-[firstButton(buttonWidth)]-[secondButton(==firstButton)]-|",
options: NSLayoutFormatOptions.AlignAllCenterY,
metrics: metrics,
views: views)
allConstraints += topRowHorizontalConstraints
let bottomRowHorizontalContraints = NSLayoutConstraint.constraintsWithVisualFormat(
"H:|-[thirdButton(buttonWidth)]-[fourthButton(==thirdButton)]-|",
options: NSLayoutFormatOptions.AlignAllCenterY,
metrics: metrics,
views: views)
allConstraints += bottomRowHorizontalContraints
let leftColumnVerticalConstraints = NSLayoutConstraint.constraintsWithVisualFormat(
"V:[firstButton]-[thirdButton(==firstButton)]-[bottomLayoutGuide]-|",
options: [],
metrics: metrics,
views: views)
allConstraints += leftColumnVerticalConstraints
let rightColumnVerticalConstriants = NSLayoutConstraint.constraintsWithVisualFormat(
"V:[secondButton(buttonHeight)]-[fourthButton(==secondButton)]-[bottomLayoutGuide]-|",
options: [],
metrics: metrics,
views: views)
allConstraints += rightColumnVerticalConstriants
NSLayoutConstraint.activateConstraints(allConstraints)
// ** DON'T SET IMAGES ON THE BUTTONS UNTIL THE BUTTONS ARE LAID OUT!!!**
firstButton.imageView?.contentMode = UIViewContentMode.ScaleAspectFit
firstButton.setImage(UIImage(named: "first.png"), forState: .Normal)
secondButton.imageView?.contentMode = UIViewContentMode.ScaleAspectFit
secondButton.setImage(UIImage(named: "second.png"), forState: .Normal)
thirdButton.imageView?.contentMode = UIViewContentMode.ScaleAspectFit
thirdButton.setImage(UIImage(named: "third.png"), forState: .Normal)
fourthButton.imageView?.contentMode = UIViewContentMode.ScaleAspectFit
fourthButton.setImage(UIImage(named: "fourth.png"), forState: .Normal)
Hello
I'm trying to put an Image as a background for my ViewControllers, guiding myself for other posts I found this way:
I created the following extension:
extension UIView {
func addBackground() {
// screen width and height:
let width = UIScreen.mainScreen().bounds.size.width
let height = UIScreen.mainScreen().bounds.size.height
let imageViewBackground = UIImageView(frame: CGRectMake(0, 0, width, height))
imageViewBackground.image = UIImage(named: "msa_background")
// you can change the content mode:
imageViewBackground.contentMode = UIViewContentMode.ScaleAspectFill
imageViewBackground.clipsToBounds = true
self.addSubview(imageViewBackground)
self.sendSubviewToBack(imageViewBackground)
}
}
I'm calling this extension in every ViewController with the following code:
override func viewDidLoad() {
super.viewDidLoad()
self.view.addBackground()
}
The problem is when I rotated the screen the image in the background don't fill all the space in the ViewController, I have checked any possible solution that I found but I can't find a way to do it.
I really appreciate any help from you
You are adding the image with the current frame of the screen and never changing it. When you rotate the device it will keep the same frame.
Change it to use AutoLayout like this...
extension UIView {
func addBackground(imageName: String, contentMode: UIViewContentMode) {
let imageViewBackground = UIImageView()
imageViewBackground.image = UIImage(named: imageName)
// you can change the content mode:
imageViewBackground.contentMode = contentMode
imageViewBackground.clipsToBounds = true
imageViewBackground.translatesAutoresizingMaskIntoConstraints = false
self.insertSubview(imageViewBackground, atIndex: 0)
self.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("|[imageViewBackground]|",
options: [],
metrics: nil,
views: ["imageViewBackground", imageViewBackground]))
self.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|[imageViewBackground]|",
options: [],
metrics: nil,
views: ["imageViewBackground": imageViewBackground]))
}
}
The auto layout constraints will then make the image view fit to the view no matter how the orientation of the device or frame of the view changes.
I have a scrollview which contains two containers (UIViews). One UIView contains a UITableView which displays correctly and another ViewController. The viewController has an image which fills it completely. However, when adding the View Controller if I set a background color that shows up.
//
// SideBarViewController.swift
// Sidebar
//
// Created by Satyajit Sarangi on 12/10/15.
// Copyright © 2015 Satyajit Sarangi. All rights reserved.
//
import UIKit
class SideBarViewController: UIViewController {
// MARK: Properties
var scrollView: UIScrollView!
let menuTableView = UITableView()
let sideBarContainerView = UIView()
let mainContainerView = UIView()
let testContainerView = UITableView()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
// Create a dictionary for the views for the visual format language
let containerViewsDict = Dictionary(dictionaryLiteral: ("sidebar_container", sideBarContainerView), ("main_container", mainContainerView))
// let scrollViewDict = Dictionary(dictionaryLiteral: ("scrollview", scrollView))
// Create two container
// Add the scroll view
scrollView = UIScrollView(frame: view.frame)
// Set Properties for scrollview
scrollView.scrollEnabled = true
scrollView.pagingEnabled = true
scrollView.contentSize = CGSizeMake(view.frame.width, view.frame.height)
// sideBarContainerView.backgroundColor = UIColor.yellowColor()
scrollView.addSubview(sideBarContainerView)
scrollView.addSubview(mainContainerView)
setupMainContainerView()
setupSideBarTableView()
// Add the Scroll View
view.addSubview(scrollView)
let horizontalConstraints = NSLayoutConstraint.constraintsWithVisualFormat("H:|[sidebar_container]-5-[main_container]|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: containerViewsDict)
let scrollview_verticalConstraints1 = NSLayoutConstraint.constraintsWithVisualFormat("V:|[sidebar_container]|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: containerViewsDict)
let scrollview_verticalConstraints2 = NSLayoutConstraint.constraintsWithVisualFormat("V:|[main_container]|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: containerViewsDict)
sideBarContainerView.translatesAutoresizingMaskIntoConstraints = false
mainContainerView.translatesAutoresizingMaskIntoConstraints = false
scrollView.translatesAutoresizingMaskIntoConstraints = false
scrollView.addConstraints(horizontalConstraints)
scrollView.addConstraints(scrollview_verticalConstraints1)
scrollView.addConstraints(scrollview_verticalConstraints2)
// Add constraints for the Scroll View
// let scrollview_constraint_v = NSLayoutConstraint.constraintsWithVisualFormat("V:|[scrollview]|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: scrollViewDict)
// let scrollview_constraint_h = NSLayoutConstraint.constraintsWithVisualFormat("H:|[scrollview]|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: scrollViewDict)
// scrollView.addConstraints(scrollview_constraint_v)
// scrollView.addConstraints(scrollview_constraint_h)
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
scrollView.frame = view.bounds
view.frame = CGRectMake(0, 0, scrollView.contentSize.width, scrollView.contentSize.height)
scrollView.setContentOffset(CGPoint(x: 100, y: 0), animated: true)
}
// MARK: Set UI Properties
func setupSideBarTableView() {
menuTableView.frame = CGRectMake(0, 0, 200, scrollView.frame.height)
menuTableView.contentSize = CGSizeMake(1000, 1000)
menuTableView.backgroundColor = UIColor.redColor()
sideBarContainerView.addSubview(menuTableView)
let dict = Dictionary(dictionaryLiteral: ("menu_table", menuTableView))
let constraint_h = NSLayoutConstraint.constraintsWithVisualFormat("H:|[menu_table]|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: dict)
let constraint_v = NSLayoutConstraint.constraintsWithVisualFormat("V:|[menu_table]|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: dict)
sideBarContainerView.frame = menuTableView.frame
sideBarContainerView.addConstraints(constraint_h)
sideBarContainerView.addConstraints(constraint_v)
}
func setupMainContainerView() {
// testContainerView.frame = CGRectMake(0, 0, 320, scrollView.frame.height)
// testContainerView.contentSize = CGSizeMake(1000, 1000)
// testContainerView.backgroundColor = UIColor.yellowColor()
let testContainerView = TestViewController()
self.addChildViewController(testContainerView)
mainContainerView.addSubview(testContainerView.view)
// let dict = Dictionary(dictionaryLiteral: ("test_container", testContainerView))
// let constraint_h = NSLayoutConstraint.constraintsWithVisualFormat("H:|[test_container]|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: dict)
// let constraint_v = NSLayoutConstraint.constraintsWithVisualFormat("V:|[test_container]|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: dict)
mainContainerView.frame = testContainerView.view.frame
// mainContainerView.addConstraints(constraint_h)
// mainContainerView.addConstraints(constraint_v)
testContainerView.didMoveToParentViewController(self)
}
}
The view controller looks like this... and the code for it is pasted below. As can be seen, the story board has the image and the viewDidLoad sets it to yellow. However, if I turn off background color, no image is seen.
import UIKit
class TestViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
self.view.backgroundColor = UIColor.yellowColor()
}
}
How do I get the TestControllerView to display the views inside it?
You are instantiating the TestViewController like so:
let testContainerView = TestViewController()
That will not use the storyboard. If you want to use the storyboard, you have give that scene a "storyboard id" in Interface Builder, and then you can programmatically to do something like:
let testContainerView = storyboard?.instantiateViewControllerWithIdentifier("TestViewController storyboard id here")
By the way, when you have these sorts of problems, it's useful to run the app from Xcode and then use the view debugger:
That lets you dynamically inspect the view hierarchy (so you can confirm whether something's really missing or just possibly off screen or otherwise not visible).
i have a custom tableCell that working fine, till i am trying to add an image on the left of each cell.
when placing the image inside the conventView all is working fine, but i don't like when the separator is starting in the middle of the image.
and i want to eliminate the space on the left of each row, i want to place my image there, so the cell seperator will show only under the cell content , and not under part of the image, i am strageling this separator for a couple of hours and now i can't show my content..
also my simulator i taking something like 10 sec to show the table content..
can u help me please, i know its suppose to be s simple thing, but i can't manage this to work...
thank you..
here is my custom TableCell
import UIKit
class TableCellMessages: UITableViewCell {
var labUerName = UILabel();
var labMessage = UILabel();
var labTime = UILabel();
var labRead = UILabel();
override func awakeFromNib() {
super.awakeFromNib()
self.imageView.clipsToBounds = true
self.imageView.layer.cornerRadius = 22;
self.imageView.contentMode = UIViewContentMode.ScaleAspectFill
// self.imageView.autoresizingMask = UIViewAutoresizing.None
var currentFont:UIFont = labUerName.font
labUerName.font = UIFont.boldSystemFontOfSize(currentFont.pointSize);
labUerName.setTranslatesAutoresizingMaskIntoConstraints(false)
labMessage.setTranslatesAutoresizingMaskIntoConstraints(false)
labTime.setTranslatesAutoresizingMaskIntoConstraints(false)
labRead.setTranslatesAutoresizingMaskIntoConstraints(false)
contentView.addSubview(labUerName)
contentView.addSubview(labMessage)
contentView.addSubview(labTime)
contentView.addSubview(labRead)
//Set layout
var viewsDict = Dictionary <String, UIView>()
viewsDict["username"] = labUerName;
viewsDict["message"] = labMessage;
viewsDict["time"] = labTime;
viewsDict["read"] = labRead;
contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-0-[username]-1-[message]", options: NSLayoutFormatOptions(0), metrics: nil, views: viewsDict))
contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-0-[time]-1-[read]", options: NSLayoutFormatOptions(0), metrics: nil, views: viewsDict))
contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-[username]-[time]-|", options: NSLayoutFormatOptions(0), metrics: nil, views: viewsDict))
contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-[message]-[read]-|", options: NSLayoutFormatOptions(0), metrics: nil, views: viewsDict))
}
override func layoutSubviews() {
super.layoutSubviews()
var x = self.frame.origin.x;
var y = self.frame.origin.y;
var width = self.frame.width;
var height = self.frame.height;
self.imageView.frame = CGRectMake(x, y, height, height);
self.contentView.frame = CGRectMake(x + height, y, width - height , height)
}
}
To fix the cell separator, you'll need to use the separatorInset property on your UITableView which you most likely have a reference to in your view controller:
self.tableView.separatorInset = UIEdgeInsets(0, 0, 0, 0)
See https://developer.apple.com/library/prerelease/iOS/documentation/UIKit/Reference/UITableView_Class/index.html#//apple_ref/occ/instp/UITableView/separatorInset
Apart from that, you'll save yourself and your fellow programmers a lot of headache if you design your custom cell as a prototype cell in your storyboard instead of laying out your labels etc programmatically.