How to programmatically create UIlabel inside a custom uiView swift - swift

how can i create 5 custom uilabel inside a custom UIView. Which will align one after the other. i have tried to create the UILabel inside the custom UIView. but it does not go inside the custom UIView.
//updated with the loop
import UIKit
class ViewController: UIViewController {
#IBOutlet weak var mainView: UIView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
var getMainViewX = mainView.frame.origin.x
let getMainViewY = mainView.frame.origin.y
for var i = 0; i < 5; i++
{
let label = UILabel(frame: CGRectMake(getMainViewX, getMainViewY, 200, 21))
//label.center = CGPointMake(160, 284)
label.textAlignment = NSTextAlignment.Center
label.text = "I'am a test label"
self.mainView.addSubview(label)
getMainViewX+=20
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}

If you're using iOS 9, the recently added Stack View has been created for exactly this purpose.
Use a UIStackView for your mainView instead of a default view
You can set the alignment properties of the stack view in Interface Builder
Create the labels in your loop, then add them to the stack view using the addArrangedSubview method of the stack view.
The stack view will take care of the alignment, spacing and layout of it's subviews for you.

Its not clear what you mean by "align".
Assuming you want them one stacked one below another, I have made minor adjustments to your code.
class ViewController: UIViewController {
#IBOutlet weak var mainView: UIView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
let getMainViewX = mainView.frame.origin.x
//let getMainViewY = mainView.frame.origin.y
for var i = 0; i < 5; i++
{
//let label = UILabel(frame: CGRectMake(getMainViewX, getMainViewY, 200, 21))
let label = UILabel(frame: CGRectMake(getMainViewX, CGFloat(i) * 21, 200, 21))
//label.center = CGPointMake(160, 284)
label.textAlignment = NSTextAlignment.Center
label.text = "I'am a test label"
self.mainView.addSubview(label)
//getMainViewX+=20
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
Hopefully this is how you are looking to align the labels

Related

How to properly size content on ScrollView for all devices?

I am using a scrollview along with Nibs. The goal is to layout 3 nibs with image inside them and scroll through them. I am also using storyboards to layout the scrollview.
The issue is venting looks good besides on the iPhone Plus sizes. The nibs are not centered right and bleeds on the screen? how do I fix this? Please check my code below.
#IBOutlet private weak var scrollView: UIScrollView!
override func viewDidLoad() {
super.viewDidLoad()
imageArray = [imageOne, imageTwo, imageThree]
scrollView.contentSize = CGSize(width: self.view.bounds.width * CGFloat(imageArray.count), height: scrollView.frame.size.height)
loadOnboardingDescriptions()
}
// MARK: Load onboarding dscription features
func loadOnboardingDescriptions() {
for (index, image) in imageArray.enumerated() {
if let onboardingDescriptionView = Bundle.main.loadNibNamed(Constants.NibName.onboardingDescriptionView.rawValue, owner: self, options: nil)?.first as? OnboardingDescriptionView {
onboardingDescriptionView.onboardingImageView.image = UIImage(named: image["image"]!)
onboardingDescriptionView.frame.size.width = self.view.bounds.size.width
onboardingDescriptionView.frame.origin.x = CGFloat(index) * self.view.bounds.size.width
print(onboardingDescriptionView.frame.origin.x)
self.scrollView.addSubview(onboardingDescriptionView)
}
}
}
EDIT:
As suggested by Matt bellow, I should have called this function inside:
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
loadOnboardingDescriptions()
}

Reset/Refesh UIscroll view

I Have a scroll view that contains multiple view controllers. On those view controllers I have switches. When on switch is "on" all the other switches turn off. This is all done through the viewDidLoad.
I cannot get this to work though, I have tried putting the code for the switch thingy stuff that I am trying to do in viewWillAppear. It seems though that these two methods are only called at run time.
My alternative idea is to somehow "reset" the scroll view from inside one of the subviews
here is what i have:
class ViewController: UIViewController {
#IBOutlet weak var scrollView: UIScrollView!
override func viewDidLoad() {
super.viewDidLoad()
let vc0 = ViewController0(nibName: "ViewController0", bundle: nil)
self.addChildViewController(vc0)
self.scrollView.addSubview(vc0.view)
vc0.didMoveToParentViewController(self)
let vc1 = ViewController1(nibName: "ViewController1", bundle:nil)
var frame1 = vc1.view.frame
frame1.origin.x = self.view.frame.size.width
vc1.view.frame = frame1
self.addChildViewController(vc1)
self.scrollView.addSubview(vc1.view)
vc1.didMoveToParentViewController(self)
let vc2 = ViewController2(nibName: "ViewController2", bundle:nil)
var frame2 = vc2.view.frame
frame2.origin.x = self.view.frame.size.width * 2
vc2.view.frame = frame2
self.addChildViewController(vc2)
self.scrollView.addSubview(vc2.view)
vc2.didMoveToParentViewController(self)
let vc3 = ViewController2(nibName: "ViewController3", bundle:nil)
var frame3 = vc3.view.frame
frame3.origin.x = self.view.frame.size.width * 3
vc3.view.frame = frame3
self.addChildViewController(vc3)
self.scrollView.addSubview(vc3.view)
vc3.didMoveToParentViewController(self)
self.scrollView.contentSize = CGSizeMake(self.view.frame.size.width * 4, self.view.frame.size.height - 66);
}
}
^for the scrollUI creator class
import UIKit
class ViewController0: UIViewController {
#IBOutlet weak var onoff: UISwitch!
override func viewDidLoad() {
super.viewDidLoad()
onoff.on = false
}
#IBAction func used(sender: AnyObject) {
let parent = self.view.superview
parent?.setNeedsDisplay()
}
}
^this is one of the subclasses
This subclass has a switch and when toggled, it should "reset" the scroll view so all of the subviews viewDidLoad are called again...
This does not work.... Are there any solutions to this??
BTW sorry for the bad formatting for the code blocks.

UIButton in UIScrollView->UIStackView->UIView not clicking

I am having trouble figuring out why a UIButton will not click. I have a UIScrollView that contains a UIStackView where I am programmatically placing subviews. I am creating the subviews and placing them into the stack view with the following:
import UIKit
class ViewController: UIViewController {
#IBOutlet weak var scrollView: UIScrollView!
#IBOutlet weak var stackView: UIStackView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
let vc0 = self.storyboard?.instantiateViewControllerWithIdentifier("vc0") as UIViewController!
let vc1 = self.storyboard?.instantiateViewControllerWithIdentifier("vc1") as UIViewController!
self.stackView.addArrangedSubview(vc0.view)
self.stackView.addArrangedSubview(vc1.view)
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
// mulitply by two in order to scale it to the size of each `addArrangedSubview`, subtract the height of the embedded navbar
scrollView.contentSize = CGSize(width: stackView.frame.width * 2, height: stackView.frame.height - 64)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
The only other changes I have made are with the constraints:
I should note that vc0 and vc1 are simple UIViews with a UIButton set to show another simple UIView.
Any help would be much appreciated!
EDIT:
I have added a button to vc0 programmatically and the click is working. Why would this button work and one from storyboard not work?
...
let vc0 = self.storyboard?.instantiateViewControllerWithIdentifier("vc0") as UIViewController!
...
let btn=UIButton(type: .System)
btn.frame = CGRectMake(100, 100, 32, 32)
btn.addTarget(self, action: "pressed", forControlEvents: .TouchUpInside)
btn.setTitle("Press Me", forState: .Normal)
vc0.view.addSubview(btw)
...

How to add constraints to a Custom UITableViewCell

I have created a custom cell for my table view and it works fine except that my Image View will not align correctly.
Is there a way to add constraints to a custom cell view? Programmatically or otherwise?
This is what my cell looks like in the storyboard - which is what I was hoping to achieve at run time:
But when I demo the app this is what happens:
Here is another image from the storyboard:
View Controller /w TableView
#IBOutlet weak var tableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
println(questions)
println(finalResults)
let theWidth = view.frame.size.width
let theHeight = view.frame.size.height
tableView.frame = CGRectMake(0,0, theHeight, theWidth)
}
Cell View Controller
override func awakeFromNib() {
let theWidth = UIScreen.mainScreen().bounds.width
contentView.frame = CGRectMake(0,0, theWidth, 64)
answerImage.center = CGPointMake(115, 15)
}
You only have to set up your constraints correctly. Indeed, even if Add Missing Constraints and Reset to Suggested Constraints are handy sometimes they don't know what you want, thus the result cannot always be what you expect.
What you might want to do here is the following.
For you question label set it in center Y of it's container and set it's leading space to the superview. Like so :
Then for you image, you want to set it in center Y of it's container too and set a ratio 1:1 on it. Like so :
Note that you might also want to check the width and height if you don't want your image to upscale (if you set a bigger cell on some device).
You should now have something like that :
And the result :
Let me know if it helped.
PS : I don't have your image so I've just set a background color on the uiimageview
Assuming that you started with a View Controller, Dragged a table and a Cell into the table...
in ViewController: UIViewController...{
#IBOutlet weak var resultsTable: UITableView! // connect to tableView
override func viewDidLoad() {
super.viewDidLoad()
let theWidth = view.frame.size.width
let theHeight = view.frame.size.height
resultsTable.frame = CGRectMake(0,0, theWidth, theHeight)
}
}
in UITableViewCell file:
#IBOutlet weak var imageView: UIImageView!
override func awakeFromNib() {
let theWidth = UIScreen.mainScreen().bounds.width
contentView.frame = CGRectMake(0,0 theWidth, 64)
imageView.center = CGPointMake(115, 15) //mess around with these #
}

Swift - changing app when banner loads. - xcode 6 GM

I have been working on a mainly text-based application with an Iadbanner in the bottom.
However as we all know, Iads aren't always there. So I would like to be able to dynamically update the height of my textView, so when the banner is hidden, the textView takes up the wasted space. And resize it when a banner is loaded.
Here's what I currently have for the Viewcontroller in question
import UIKit
import iAd
class DetailVC: UIViewController, UITextViewDelegate, ADBannerViewDelegate {
//Our label for displaying var "Items/cellName"
#IBOutlet var imageViewOutlet: UIImageView!
//connect in IB connection inspector with your ADBannerView
#IBOutlet var adBannerView: ADBannerView!
//Receiving variable assigned to our mainVC var "items"
var cellName: String = ""
var imageView: UIImageView = UIImageView()
var image = UIImage(named: "handcuffs.png")
var textViewText: String = ""
var textView: UITextView = UITextView(frame: CGRect(x: 5.0, y: 238.0, width: 315.00, height: 283.00))
//height = 332 for full screen 283 for small
override func viewDidLoad() {
super.viewDidLoad()
println("+--------------------+")
println("| Detail view loaded |")
println("+--------------------+")
// Iad stuff
self.adBannerView.delegate = self
self.canDisplayBannerAds = true
self.adBannerView.hidden = true //hide until ad loaded
//Setting up the textView
textView.text = textViewText
textView.editable = false
textView.backgroundColor = UIColor.clearColor()
textView.font = UIFont(name: "Helvetica", size: 15)
//adding textview as subview
self.view.addSubview(textView)
//ImageViewOutlets
imageViewOutlet.image = image
//Assign your string var to your navbar title
self.title = cellName
func bannerViewWillLoadAd(banner: ADBannerView!) {
NSLog("bannerViewWillLoadAd")
}
func bannerViewDidLoadAd(banner: ADBannerView!) {
NSLog("bannerViewDidLoadAd")
//self.textView.removeFromSuperview()
//textView = UITextView(frame: CGRect(x: 0.0, y: 238.0, width: 320.00, height: 283.00))
//self.view.addSubview(textView)
self.adBannerView.hidden = false //now show banner as ad is loaded
}
func bannerViewActionDidFinish(banner: ADBannerView!) {
NSLog("bannerViewActionDidFinish")
//optional resume paused app code
}
func bannerViewActionShouldBegin(banner: ADBannerView!, willLeaveApplication willLeave: Bool) -> Bool {
NSLog("bannerViewActionShouldBegin")
//optional pause app code
return true
}
func bannerView(banner: ADBannerView!, didFailToReceiveAdWithError error: NSError!) {
NSLog("didFailToReceiveAdWithError")
}
//... your class implementation code
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
The commented out code in the function "bannerViewDidLoadAd" is what I thought would have fixed my issue. Sadly that function seems to never run? I'm not very familiar with Iads so hopefully someone out there can give me a hint as to how to change the height of a textView when an ad loads.
CanDisplayBannerAds :
Set this to enable automatic management of banner ad display with the view controller. It's important to note that this will modify the view hierarchy of the view controller by inserting a new container view above the view controller's view. The impact is that the view controller's view property will no longer return the originally provided view, it will return the new container. To access the original view, use the originalContentView property.
So, remove this line :
self.canDisplayBannerAds = true
Everything should work.