Add label to point - ios

I have followed this tutorial: https://www.raywenderlich.com/410-core-graphics-tutorial-part-2-gradients-and-contexts
I am trying to add a label over each point with the Int for the point, but it wont show. Adding code in the //Draw the circles on top of graph stroke
//Draw the circles on top of graph stroke
for i in 0..<graphPoints.count {
var point = CGPoint(x:columnXPoint(i), y:columnYPoint(graphPoints[i]))
point.x -= Constants.circleDiameter / 2
point.y -= Constants.circleDiameter / 2
let circle = UIBezierPath(ovalIn: CGRect(origin: point, size: CGSize(width: Constants.circleDiameter, height: Constants.circleDiameter)))
circle.fill()
//let label = UILabel(frame: CGRect(origin: point, size: CGSize(width: Constants.circleDiameter, height: Constants.circleDiameter)))
let label = UILabel()
label.frame.origin = CGPoint(x:columnXPoint(i), y:columnYPoint(graphPoints[i]))
label.text = "TDDDDDDDE"
label.translatesAutoresizingMaskIntoConstraints = false
label.textColor = UIColor.black
self.addSubview(label)
self.view.addSubview(label)
}
Can anyone help me with adding the label? The label wont show, and I want it over the points.

Best guests, given there's not the full context. I see 3 possible reasons
1: You should replace
self.addSubview(label)
self.view.addSubview(label)
By
self.addSubview(label)
The second line will remove the label from view to add it to self.view, which might be a problem if they are different.
2: With the following line, you're telling the label to use autolayout ...but do not provide any constraint, so they might be there but not where you expected them to be.
label.translatesAutoresizingMaskIntoConstraints = false
To add constraints: see official Apple Doc, example below:
label.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: aConstant).isActive = true
But 3: your label is initialised without a frame/an empty frame. Call sizeToFit on your label after having set the content, fonts, etc if you don't use autolayout. If you stick to autolayout, this point is not applicable.
And another point indirectly linked to your question: If you manage to get your code to work, you'll probably have too much labels: your code seems to be in the draw method, which means that you'll be instantiating new labels each time the view is rendered ...and the previous ones won't be removed. A better practice would be instanciate the labels when you load the data (if they depend on the data points), to position them in layoutSubviews or to skip the labels entirely and use NSAttributedString draw functions to render the text directly in the view.

Related

How to wrap text in Swift 5

Brand new to Xcode and Swift, but I'm trying to have a headline and subheading for a news type app I'm prototyping out. I can't get the text to wrap, leaving out most of the headline and brief summary. I need it to say
Unity with purpose. Amanda Gorman and Michelle Obama Discuss Art Identity and Optimism
Amanda Gorman captivated the world when she read her poem “The Hill We
Climb” at President Joe Biden and Vice President Kamala Harris’ Jan.
20 Inauguration ceremony.
All I get is:
Here is the code generating the labels, this is the headline but they are basically the same:
private let headlineLabel: UILabel = {
let label = UILabel()
label.textAlignment = .left
label.textColor = .white
label.font = UIFont.preferredFont(forTextStyle: .largeTitle) //Scales font automatically
label.adjustsFontForContentSizeCategory = true //Adjusts font sized based on settings user has
label.lineBreakMode = .byWordWrapping
label.numberOfLines = 0
return label
}()
I've tried setting numberOfLines = 0 as well as label.lineBreakMode = .byWordWrapping and neither seem to work.
How can I get the entire string for both the headline and subheading to be displayed?
Thanks!
The properties that you applied to your UILabel to allow wrapping looks correct, but
without seeing more of the code it's hard to tell. So I'm betting it's your horizontal layout constraints (if any). If you did not set an explicit frame to your view. Then ensure you're setting+activating vertical and horizontal constraints for your view.
// Important step to enable contraints
label.translatesAutoresizingMaskIntoConstraints = false
....
// Important that you add your view to the view hierarchy first before activating
// constraints. If not this will produce a runtime error.
self.view.addSubview(label)
....
NSLayoutConstraint.activate([
label.leadingAnchor.contraint(equalTo: self.view.leadingAnchor)
label.trailingAnchor.contraint(equalTo: self.view.trailingAnchor)
label.topAnchor.contraint(equalTo: self.view.topAnchor)
])
The .activate(:) is another important step and common pitfall. Ensure you're activating your contraints!
leadingAnchor is attaching the left side of your label's frame to the left side of your parent view.
trailingAnchor is doing the same thing, but for the right side.
Then finally we pin the label to the top of the parent view. You may want use .contraint(equalTo: .., constant: ..) to push your label down a little bit as well.
So, in the next update loop and when your parent view lays out the subviews. Your label's frame will be calculated based on your activated constraints. So in this case your label's frame will look something like this (x:0, y:0, width: 300, height: *height is intrinsic here) This is assuming a parent frame of (x: 0, y: 0, width: 300, height: 600)
You mentioned you're new to iOS, so I hope this info helps you in some way.

How to force word wrapping of UILabel that adjusts font size and is multiline

The problem I am facing is that UILabel will break line in the middle of the word although I am using word wrapping.
You can create a new project and replace content of view controller to see the result:
override func viewDidLoad() {
super.viewDidLoad()
let label = UILabel(frame: CGRect(x: 0.0, y: 0.0, width: 100.0, height: 100.0))
label.center = CGPoint(x: view.frame.midX, y: view.bounds.midY)
label.numberOfLines = 2 // Setting this to 1 produces expected result
label.lineBreakMode = .byWordWrapping
label.adjustsFontSizeToFitWidth = true
label.minimumScaleFactor = 0.5
view.addSubview(label)
label.text = "Singlewordtext"
label.backgroundColor = .red
}
This produces 2 lines of text which is broken in the middle of the word. The reason this naturally happens is because the word itself is wider than the label itself so it makes sense (I guess). But I would hope that it would use adjustsFontSizeToFitWidth and minimumScaleFactor prior to breaking it. If I set it to single line (label.numberOfLines = 1) I get expected result which is that the text will shrink instead of break. Note that doing so in this case will fit all of the text inside the label.
The question is, is there a configuration on UILabel to prevent line break in such case? Or is there some other elegant solution?
A current result:
Desired result (produced by using label.numberOfLines = 1):
Do note that I still do need to have 2 lines enabled to nicely display for instance label.text = "Three words fit".

Moving Labels within External Screen

I'm wanting to move my labels wherever I want on my external display. (eg. displayRunsLabel at the top and centered or perhaps 40px from right and top)
I have my labels showing on the screen. I'm currently using text alignment.
What's the best way to do this?
Here's my external display:
ExternalDisplayScreenshot
Here's the code:
// CUSTOMISE VIEW
secondScreenView.backgroundColor = UIColor.black
displayWicketLabel.textAlignment = NSTextAlignment.left
displayWicketLabel.font = UIFont(name: "Arial-BoldMT", size: 200.0)
displayWicketLabel.textColor = UIColor.white
displayWicketLabel.frame = secondScreenView.bounds
secondScreenView.addSubview(displayWicketLabel)
displayRunsLabel.textAlignment = NSTextAlignment.center
displayRunsLabel.font = UIFont(name: "Arial-BoldMT", size: 200.0)
displayRunsLabel.textColor = UIColor.white
displayRunsLabel.frame = secondScreenView.bounds
secondScreenView.addSubview(displayRunsLabel)
displayOversLabel.textAlignment = NSTextAlignment.right
displayOversLabel.font = UIFont(name: "Arial-BoldMT", size: 200.0)
displayOversLabel.textColor = UIColor.white
displayOversLabel.frame = secondScreenView.bounds
secondScreenView.addSubview(displayOversLabel)
}
The position of a label or any other UIView is the origin of its frame, which is a CGPoint representing its top left corner.
So, you are currently saying:
displayWicketLabel.frame = secondScreenView.bounds
displayRunsLabel.frame = secondScreenView.bounds
displayOversLabel.frame = secondScreenView.bounds
Well, that's pretty silly, because you have given all three labels the same frame! Thus they overlay one another, and (as you rightly say) you can only read them by giving them different text alignments.
Instead, give them each a different frame — one that puts the label where you want it. For example:
displayWicketLabel.sizeToFit()
displayWicketLabel.frame.origin = CGPoint(x:30, y:20) // or whatever
displayRunsLabel.sizeToFit()
displayRunsLabel.frame.origin = CGPoint(x:30, y:100) // or whatever
displayOversLabel.sizeToFit()
displayOversLabel.frame.origin = CGPoint(x:30, y:200) // or whatever
Now, having said all that, a clear flaw in the code I just showed you is that we have hard-coded the positions arbitrarily, without taking account of what the size of the window is (the external display). For that reason, a much better way would be for you to learn about auto layout, which will let you lay the three labels out in nice positions automatically based on the size of the window.

Why aren't the backgrounds within these UITextViews clear?

I am attempting to display individual characters in the exact positions that they would appear if displayed as a single string with kerning. The problem is that the characters' bounding boxes seem to be opaque, so that each newly added character covers some of the prior one. Where kerning is greater (e.g., in the combination "ToT"), the problem is obvious:
My setup is something like this: I have an SKView embedded in a container view. In an extension of the SKView's view controller, the following are set within a function in this order:
skView.allowsTransparency = true
scene.backgroundColor = .clear
charAttr – [NSAttributedStringKey.backgroundColor: UIColor.clear]
textView.isOpaque = false
textView.backgroundColor = UIColor.clear
Each UITextView is added successively as a subview to the view (which is an SKView).
I've looked all over my code for some clue as to what could be making the character's bounding boxes seem opaque, but I haven't found anything. The sad thing is that I solved this problem sometime last year, but don't remember what I did and don't have the code anymore.
Any insights or ideas would be appreciated.
After achieving the sought-after effect in a playground, I pasted this simple code into the extension where the original code was. It still worked, so I made it as close to identical to the original as possible, until it also exhibited the problem.
The SKView and extension aspects were irrelevant. The problem lies with how UITextView frames property deals with character widths. Here's the relevant code:
// charInfoArray contains (among other things) an attributed character, its origin,
// its size, and info about whether or not it should be displayed
// For each char, the origin and size info were derived from...
let currentCharRect = layoutManager.boundingRect(forGlyphRange: currentCharRange, in: textContainer)
// To display each (attributed) char of "ToT\n" . . .
for (index, charInfo) in charInfoArray.enumerated() {
guard charInfo.displayed == true else { continue }
let textView = UITextView()
textView.backgroundColor = UIColor.clear
textView.attributedText = charInfo.attrChar
textView.textContainerInset = UIEdgeInsets.zero
// let width = charInfo.size!.width
let width = 30 // arbitrary width
// Using the automatically generated charInfo.size!.width here
// appears to make the text view's background opaque!
textView.frame = CGRect(origin: charInfo.origin!,
size: CGSize(width: width, height: charInfo.size!.height))
textView.frame = textView.frame.offsetBy(dx: 0.0, dy: offsetToCenterY)
textView.textContainer.lineFragmentPadding = CGFloat(0.0)
textView.backgroundColor = UIColor(red: 1, green: 0, blue: 0, alpha: 0.2)
textView.textColor = UIColor.black
view.addSubview(textView)
print(charInfo.size!.width)
}
Setting the width to width = charInfo.size!.width seems to make the text view's background opaque! This may be caused by the unusually large width assigned to newline char at the end of the sequence. To eliminate the problem, I'll have to deal with newline chars in another way. In any case, I have no idea why this causes the text view's background to turn opaque, but it does. Setting the width to an arbitrary value of, say, 30 eliminates problem.
Here are the results of using automatically generated and manually set widths, respectively:
The translucent red areas (on yellow backgrounds) show the bounding rectangles for each of the characters, including the newline character.

Swift Dynamically created UILabel shows up twice

I have written a custom graph UIView subclass, and I use it to graph some basic data, and insert some user-defined data. As a final step, I'd like to add a UILabel on top of the graph with the user-defined data-point called out.
I highlight the point, and then create and add the UILabel:
if(graphPoints[i] == highlightPoint){
var point2 = CGPoint(x:columnXPoint(i), y:columnYPoint(graphPoints[i]))
point2.x -= 8.0/2
point2.y -= 8.0/2
let circle2 = UIBezierPath(ovalInRect:
CGRect(origin: point2,
size: CGSize(width: 8.0, height: 8.0)))
highlightColor.setFill()
highlightColor.setStroke()
circle2.fill()
let circle = UIBezierPath(ovalInRect:
CGRect(origin: point,
size: CGSize(width: 5.0, height: 5.0)))
UIColor.whiteColor().setFill()
UIColor.whiteColor().setStroke()
circle.fill()
var pointLabel : UILabel = UILabel()
pointLabel.text = "Point = \(graphPoints[i])"
pointLabel.frame = CGRectMake(point2.x, point2.y, 100, 50)
self.addSubview(pointLabel)
} else {
let circle = UIBezierPath(ovalInRect:
CGRect(origin: point,
size: CGSize(width: 5.0, height: 5.0)))
UIColor.whiteColor().setFill()
UIColor.whiteColor().setStroke()
circle.fill()
}
This looks like it should work, but the UILabel is added twice. What am I doing wrong?
This code is probably in drawRect. You're doing subview-adding in drawRect which is incorrect. drawRect gets called at least twice as the view appears, and perhaps many times after that.
You should be overriding some early lifecycle method, like awakeFromNib() or the constructor. In that, construct your label and add it as a child view. This way the addSubView() happens once as it should. The label will be invisible having no contents, so don't worry about that.
In drawRect, just update all the necessary attributes of the label including the frame.
If you find you're actually needing lots of text "labels" that come and go, different quantity for every graph, you don't really want UILabels as subviews after all. Consider directly drawing text on screen with someString.drawAtPoint(...)

Resources