How can I increase the y of a label, in swift? - swift

So I am very new in Swift and I can't figure out how to increase the y value from a label.
I am trying to show in a label, some messages that a user types in an input... like a chat view.
So I have this code, but it puts all the messages one above the other:
I know that it is very messy, I am sorry for that.
Thanks!
//my label
#IBOutlet weak var label: UILabel!
//my text field
#IBOutlet weak var textF: UITextField!
#IBAction func buttonPressed(sender: AnyObject) {
//create a variable(input) to store my text from the TextField
var input = textF.text
//put that text in the label
label.text = input
var label2 : UILabel = UILabel(frame: CGRectMake(20, 20, 200, 21))
var isSendMessage: Bool = true {
didSet {
if isSendMessage {
var input = textF.text
label.text = input
textF.text = " "
// self.view.label.origin.y += 10
} else {
var input = textF.text
label2.text = input
textF.text = " "
}
}
}
label2.center = CGPointMake(160, 284)
label2.textAlignment = NSTextAlignment.Center
self.view.addSubview(label2)
//empty text field
textF.text = " "
label2.center = CGPointMake(160, 284)
label2.textAlignment = NSTextAlignment.Center
label2.text = input
//add it to the view
self.view.addSubview(label2)
}

Try this
Don't update Y axis directly as if your Y value is greater than the screen height then label will go off the screen.
Try the following code.
// Taking height and width of the screen
var height = UIScreen.mainScreen().bounds.size.height;
var width = UIScreen.mainScreen().bounds.size.width;
var x = 164.0 // Fixed height of the label
if x < height
{
x += 20.0 // Incrementing height value
if (height - 20) >= x // Checking the difference between screen height and x, so it doesn't go beyond the screen.
{
label.frame = CGRectMake(20.0, x, 200.0, 21.0)
self.view.addSubview(label)
}
else
{
// Setting default height
label.frame = CGRectMake(20.0,164.0, 200.0, 21.0)
self.view.addSubview(label)
}
}
Hope this will be helpful.

In a quick answer to your question, if you are just looking to change the position on the y-axis you can use the property .y under .center
self.yourLabel.center.y = self.yourLabel.center.y + 10

Related

Layout programmatically created UILabels in a UIView

I have this:
Created via this piece of code:
// Add hashtag collection to a post
func addHashtags(container: UIView, constraint: NSLayoutConstraint) -> Void {
let screenSize: CGRect = UIScreen.main.bounds
let screenWidth = screenSize.width - 16 - 16
var currentOriginX: CGFloat = 0
var currentOriginY: CGFloat = 0
for j in 0..<self.pseudo.count {
if currentOriginY < 144 {
// Create a new label
let labelHashtag = RoundedLabel()
labelHashtag.rounded = true
tagLabels.append(labelHashtag)
print(tagLabels.count)
// Set its properties (title, colors, corners, etc)
labelHashtag.text = pseudo[j] as? String
labelHashtag.font = UIFont.systemFont(ofSize: 12, weight: .semibold)
labelHashtag.textAlignment = .center
labelHashtag.textColor = UIColor.black
labelHashtag.backgroundColor = UIColor.white
labelHashtag.layer.borderColor = UIColor(red:0.88, green:0.88, blue:0.88, alpha:1.0).cgColor
labelHashtag.layer.borderWidth = 1
// Set its frame width and height
labelHashtag.frame.size.width = labelHashtag.intrinsicContentSize.width + tagPadding
labelHashtag.frame.size.height = tagHeight
// Add it to the scroll view
container.addSubview(labelHashtag)
// If current X + label width will be greater than container view width
// .. move to next row
if (currentOriginX + labelHashtag.frame.width > screenWidth) {
tagLabels[0].textColor = .red
print("übrig")
print(screenWidth - currentOriginX)
currentOriginX = 0
currentOriginY += tagHeight + tagSpacingY
}
// Set the btn frame origin
labelHashtag.frame.origin.x = currentOriginX
labelHashtag.frame.origin.y = currentOriginY
// Increment current X by btn width + spacing
currentOriginX += labelHashtag.frame.width + tagSpacingX
} else if currentOriginY == 90 {
}
// Update container view height
constraint.constant = currentOriginY + tagHeight
}
container.layoutIfNeeded()
}
I want to center all items in each row. I imagine I have to calculate the remaining width of my UIView and add a margin to the first item.
How can I add a margin to my UILabel? I can access it via tagLabels[0] and I think I know how to calculate the remaining width, but I don't know how I can add the margin to it.

Multiple UILabel in Page Control

I am trying to do a scrollView + pageControl for multiple UILabel i.e. each view should have 2 UILabel - one for title and one for descriptions.
I am familiar with adding a single UILabel into scrollView + pageControl. The question is how do I add more than one UILabel into the scrollView's subview? I have the following code which works fine for a single UILabel:
#IBOutlet weak var bloggerReviewScrollView: UIScrollView!
#IBOutlet weak var bloggerReviewPageControl: UIPageControl!
var frame = CGRect(x: 0, y: 0, width: 0, height: 0)
var reviews: [Reviews] = [Reviews(name: "NameA", description: "DescriptionA", date: Date.init(), url: nil), Reviews(name: "NameB", description: "DescriptionB", date: Date.init(), url: nil)]
func updateReview() {
reviewPageControl.numberOfPages = reviews.count
for index in 0..<reviews.count {
frame.origin.x = reviewScrollView.frame.size.width * CGFloat(index)
frame.size = reviewScrollView.frame.size
let reviewContent = UILabel(frame: frame)
reviewContent.text = reviews[index].description
reviewContent.numberOfLines = 0
reviewScrollView.addSubview(reviewContent)
}
reviewScrollView.contentSize = CGSize(width: reviewScrollView.frame.size.width * CGFloat(reviews.count), height: reviewScrollView.frame.size.height)
reviewScrollView.delegate = self
}
However, other than reviews[index].description, I also want to display reviews[index].name in a different label so that the style for that label is independent of the style of the description label in the view. Are there any ways for me to do so?
Thanks a bunch!
What you need is to decide where and how you want to display your both labels, meaning label frames, I have divided into two parts you can change the frame based on your requirement and create new Label instance and add that to your reviewScrollView
func updateReview() {
reviewPageControl.numberOfPages = reviews.count
for index in 0..<reviews.count {
frame.origin.x = reviewScrollView.frame.size.width * CGFloat(index)
frame.size = reviewScrollView.frame.size
//title lable
////set title frame based on your requirment
let reviewLabelFrame = CGRect(x: frame.origin.x, y: 0, width: frame.width, height: frame.height/2)
let titleLabel = UILabel(frame: reviewLabelFrame)
titleLabel.text = reviews[index]. name // get name and set the title
titleLabel.numberOfLines = 0
reviewScrollView.addSubview(titleLabel)
//descriptions Label
//set descriptions frame based on your requirment
let desLableFram = CGRect(x: frame.origin.x, y: frame.height/2, width: frame.width, height: frame.height/2)
let desLable = UILabel(frame: desLableFram)
desLable.text = reviews[index].description //get description and set
desLable.numberOfLines = 0
reviewScrollView.addSubview(desLable) //add your descriptions
}
you need to calculate the frames for both the label based on your requirement

Re-arrange UILabel after new line

I have a label which gets its text from textfield and has a limit in width of imageview where it is on. I want to add a new line when the limit has reached. However, i couldn't do it with "\n" and wordwrapping function. In addition, i need to set UILabel's height and width to exactly texts size. I mean if it has two lines height should for two line only not much and exact same for the width property.
func textFieldShouldEndEditing(_ textField: UITextField) -> Bool {
if(imageview.frame.width > label.frame.width + 2)
{
label_test.text = "\(label.frame.width)"
label.text = textfield.text
if(imageview.frame.width < label.frame.width + 20)
{
label.lineBreakMode = .byWordWrapping
label.text = textfield.text! + "\n"
label.textAlignment = NSTextAlignment.center;
}
}
return true
}
Why can't you use lineBreakMode ? In my opinion you should define a basic setup in your viewDidLoad or so :
func viewDidLoad() {
//Your stuff
label.frame.size.width = imageview.frame.width //Define max width
label.numberOfLines = 0 //Set infinite number of lines
label.lineBreakMode = .byWordWrapping
}
Then in your textfieldShouldEndEditing you set the text and the height
label.text = textfield.text
label.sizeToFit() //The height is adjusted

calculating UIWebView height with images gives wrong answer

I found how to calculate dynamic uiwebview height according to its content. My code is :
println("webViweDidFinish started")
var frame:CGRect = myWebView.frame
frame.size.height = 1
var fittingSize :CGSize = myWebView.sizeThatFits(CGSizeZero)
frame.size = fittingSize
myWebView.frame = frame
var contentsizeHeight = webView.scrollView.contentSize.height
var yCoordinateOfWebView = myWebView.frame.origin.y
var contentHeight: CGFloat = webView.scrollView.contentSize.height;
myScrollView.contentSize = CGSizeMake(self.view.frame.width, yCoordinateOfWebView + contentsizeHeight + labelAuthorOfArticle.frame.height) //
UIView.animateWithDuration(0.5, animations: {
self.heightConstraints.constant = fittingSize.height
self.myWebView.layoutIfNeeded()
self.myScrollContentView.layoutIfNeeded()
})
self.activityIndicator.stopAnimating()
If I use this approach:
var height:NSString! = webView.stringByEvaluatingJavaScriptFromString("document.height;")
var heightInFloat = height.floatValue
How to convert height to CGFloat? I can only convert it to float as you see.
The problem is that when webview has too many images the height is calculated wrong. Oppositely when there is no image height is calculated right. When I reload the function, the second time it calculates right (with images). Here is content of string that I am loading:
class func formatContentText(inout text: NSString)-> NSString{
text = text.stringByReplacingOccurrencesOfString("src=\"", withString: "src=\"http://dixinews.kz")
var deviceWidth = "300"
text = "<html><head><meta name = \"viewport\" content = \"user-scalable=no, width=" + deviceWidth + " , maximum-scale=1.0\"><style>img{max-width:100%%;height:auto !important;width:auto !important;};</style></head><body>" + text + "</body></html>"
return text
}
I used approach with javascript. Here is my code:
func webViewDidFinishLoad(webView: UIWebView) {
var frame:CGRect = myWebView.frame
// javascript
var height:NSString! = webView.stringByEvaluatingJavaScriptFromString("document.height;")
var heightInFloat = height.floatValue // convert to float
var heightINCGFloat = CGFloat(heightInFloat) convert to cgfloat
frame.size.height = heightINCGFloat //set heigh
myWebView.frame = frame // set frame
myWebView.scrollView.contentSize.height = myWebView.frame.height
var contentsizeHeight = webView.scrollView.contentSize.height
var yCoordinateOfWebView = myWebView.frame.origin.y
myScrollView.contentSize = CGSizeMake(self.view.frame.width, yCoordinateOfWebView + contentsizeHeight + labelAuthorOfArticle.frame.height) //
UIView.animateWithDuration(0.5, animations: {
self.heightConstraints.constant = heightINCGFloat
self.myWebView.layoutIfNeeded()
self.myScrollContentView.layoutIfNeeded()
})
self.activityIndicator.stopAnimating()
}

create an equal space between labels in the scrollview with swift

I am creating a menu of the same style as the kiosk play Application
I would like the same space between labels, for I dynamically creates, I try SEVERAL way but it does not work.
I size of their label and I added the padding but it does work.
Here is the result
here is my code
func menu (value: [String]){
var pos: CGFloat = 50.0
var index: Int = 0
for index = 0; index < value.count ; index++ {
self.titleLabel = UILabel()
self.titleLabel.text = "\(value[index])"
self.titleLabel.textColor = UIColor.blackColor()
self.titleLabel.backgroundColor = UIColor.blueColor()
self.titleLabel.font = UIFont(name: "MarkerFelt-Wide", size: 20)
self.titleLabel.sizeToFit()
//width of the label
var widhtLabel = self.titleLabel.frame.size.width
// add padding
self.titleLabel.frame.origin.x = widhtLabel + pos
self.scrollViewMenu.addSubview(self.titleLabel)
pos += 150.0
println()
}
self.scrollViewMenu.contentSize = CGSize(width: self.titleLabel.frame.origin.x + 220, height:0)
}
thanks