Reputation: 865
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.
}
}
Upvotes: 3
Views: 13007
Reputation: 1195
If you're using iOS 9, the recently added Stack View has been created for exactly this purpose.
mainView
instead of a default viewaddArrangedSubview
method of the stack view.The stack view will take care of the alignment, spacing and layout of it's subviews for you.
Upvotes: 1
Reputation: 1099
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
Upvotes: 1