How to display a string/int within a UIView in Swift? - swift

this is a very simple question, but I can't find an answer anywhere. I am trying to display a high score within a CGRect, but cannot figure out exactly how to do it. I am currently trying to do this on a playground so that might have something to do with it. Thanks for the help.

You can make a UILabel in a Swift playground. Here's how it might look:
Here's the code from the playground:
import UIKit
let score = 200
let label = UILabel(frame: CGRect(x: 0, y: 0, width: 300, height: 20))
label.backgroundColor = UIColor.purpleColor()
label.textColor = UIColor.orangeColor()
label.text = "High Score: \(score)"

A CGRect is the frame or dimensions assigned to a UIView, not the UIView itself. I would suggest creating a UILabel and add that to your view. You can set the text on the UILabel to, in your case, the high score variable as a string. Im not sure if it is possible to do this in a playground, but I may be mistaken. A XCode project would work perfect for this, but again, im not sure about the playground.

To do this in a playground, it would look like this:
import UIKit
import XCPlayground
let view = UIView(frame: CGRectMake(0,0,500,500)) //create a view and give it a proper size
let label = UILabel(frame: CGRectMake(0,0,100,23)) //create a label with a size
label.text = "My Label" //give the label some text
view.backgroundColor = UIColor.lightGrayColor() //default view in Playground as black background
view.addSubview(label) //add the label to the view
XCPlaygroundPage.currentPage.liveView = view //tell playgound to display your view as the root view in the assistant editor
You need to open the assistant editor in the playground to see the result (the two circles icon in the upper right corner)

Related

How to vertically align text of NSSecureTextField in swift for macOS [duplicate]

I have been reading through the various options on how to set the vertical alignment on an NSTextField. I want the text to be displayed in the center and to do it programatically in Swift. Here are the things I have looked so far:
http://www.cocoabuilder.com/archive/cocoa/174994-repositioning-an-nstextfieldcell.html
https://red-sweater.com/blog/148/what-a-difference-a-cell-makes
Vertically Centre Text in NSSecureTextField with subclassing
Get NSTextField contents to scale
vertically align text in a CATextLayer?
One thing I have tried in Swift is to set the following property:
textField.usesSingleLineMode = true
Any tips on the best way to vertically center text would be much appreciated!
This is very hard to do, as Apple makes this very difficult. I achieved it by subclassing NSTextFieldCell and overriding the drawingRectForBounds: method like so:
override func drawingRectForBounds(theRect: NSRect) -> NSRect {
let newRect = NSRect(x: 0, y: (theRect.size.height - 22) / 2, width: theRect.size.width, height: 22)
return super.drawingRectForBounds(newRect)
}
This is just my way to do it, I'm sure there are better ways, which I don't know (yet). And this only works for the standard font size in TextFields (which gives a text height of 22). That's why I hardcoded that. Haven't figured out yet, how to get the height in the cell if you change the font.
Result:
Try this on a playground, it centers the text perfectly, use it on your projects! Hope it helps!
import Cocoa
let cell = NSTableCellView()
cell.frame = NSRect(x: 0, y: 0, width: 100, height: 100)
let tf = NSTextField()
tf.frame = cell.frame
tf.stringValue = "MyTextfield"
tf.alignment = .Center
let stringHeight: CGFloat = tf.attributedStringValue.size().height
let frame = tf.frame
var titleRect: NSRect = tf.cell!.titleRectForBounds(frame)
titleRect.size.height = stringHeight + ( stringHeight - (tf.font!.ascender + tf.font!.descender ) )
titleRect.origin.y = frame.size.height / 2 - tf.lastBaselineOffsetFromBottom - tf.font!.xHeight / 2
tf.frame = titleRect
cell.addSubview(tf)
I have added the NSTextField inside a NSView and centered it.
Another solution was (in an iOS project) to create a UILabel and allow it adjust its size (sizeToFit()) and again embed it inside a UIView.
I personally don't like the calculations in previous answers and the second solution for iOS works for all texts size and row numbers.
I was also facing vertical alignment issue with NSTextField. My requirement involved, rendering a single-line string inside a NSTextField. Additionally,
textfield needed to be resize implying we had programatically resized the font-point-size of the text inside text-field on resize. In this scenario we faced vertical-alignment issues - the mis-alignment was tough to grasp/understand in a straight forward way.
What finally worked:
So, in my scenario a simple,
turn off the "Single Line Mode" in interface builder
for the text-field solved the issue.
The accepted answer works perfectly and here's the Swift3 version.
class VerticallyAlignedTextFieldCell: NSTextFieldCell {
override func drawingRect(forBounds rect: NSRect) -> NSRect {
let newRect = NSRect(x: 0, y: (rect.size.height - 22) / 2, width: rect.size.width, height: 22)
return super.drawingRect(forBounds: newRect)
}
}

Button with multiple accessible labels and images in Swift

I need to create custom button class, reuse it 4 times and I also need to override its text and image name. My next problem is how to set its frame somehow dynamically (now it is static), because I need this 4 buttons in grid 2x2.
I'm trying to create button exactly like this: https://imgur.com/a/dNhUGhc.
I have coded this but it is static and in ViewController I can't edit (override) these labels and image name. And if I tried to reuse this class I would have them in the same spot, because frame settings is exactly the same.
I'm subclassing UIButton. If something more suitable exists just let me know.
Code for adding label
// city label
let cityRect = CGRect(x: 0, y: 20, width: buttonWidth, height: 25)
let cityLabel = UILabel(frame: cityRect)
cityLabel.text = "Label"
cityLabel.font = UIFont.systemFont(ofSize: 17, weight: .semibold)
cityLabel.textAlignment = .center
addSubview(cityLabel)
Code for adding image
// image
let imageView = UIImageView(image: UIImage(named: "something"))
imageView.frame = CGRect(x: 0, y: 60, width: 40, height: 40)
imageView.center.x = self.center.x - 20
addSubview(imageView)
Can you guys help me? Thanks
It looks like what you need to do is use an IBOutlet. Basically, an IBOutlet will give you a reference within your code (custom UIView or UIViewController subclass) to the button that you've setup in xib or storyboard. Then you can make any changes or adjustments that you want to it at runtime.
Check this out to learn more about IBOutlets and how to set them up in your project.

How to insert Custom Label with text into View with Animation?

Im making a small boxing app. This whole week iv been trying to work out how to solve my current problem above, with no luck :(.
Summary
Basically Its a 1 v 1 game. Each time the user hits the other player I want to make a tiny number pop up near him and float up and dissappear.
Its sort of like when you play MMORPG's and when you do dmg you see how much you did. See image below for an example!
So basically everytime the user hits the other player I want a little number to pop up on the screen to show the dmg and then float up and disappear.
Details
I am building the game on a simple UIView
The label is a UILabel
Anywhere How I can achieve this?
Thank you!
Create a label, then use UIView.animateWithDuration to animate it.
let label = UILabel(frame: CGRect(origin: point/*The point where you want to add your label*/, size: CGSize(width: 50, height: 50)))
label.text = "+1"
label.font = UIFont()//Your font
label.textColor = UIColor.blueColor()
label.alpha = 1
self.view.addSubview(label)
UIView.animateWithDuration(1) {
label.center = CGPoint()//The point where you want your label to end up
label.alpha = 0
}
Edit: As mentioned in the comments, you asked for how to create the label at a random point. Try this:
let screenWidth = self.view.frame.width
let screenHeight = self.view.frame.height
let randomX = CGFloat(arc4random_uniform(UInt32(screenWidth)))
let randomY = CGFloat(arc4random_uniform(UInt32(screenHeight)))
let point = CGPoint(x: randomX, y: randomY)
As you will notice, for the width and height, I use the view's frame's width and height. You may want to use the view's bounds. For more on this, check out this SO Post.

Vertically aligning text in an NSTextField using Swift

I have been reading through the various options on how to set the vertical alignment on an NSTextField. I want the text to be displayed in the center and to do it programatically in Swift. Here are the things I have looked so far:
http://www.cocoabuilder.com/archive/cocoa/174994-repositioning-an-nstextfieldcell.html
https://red-sweater.com/blog/148/what-a-difference-a-cell-makes
Vertically Centre Text in NSSecureTextField with subclassing
Get NSTextField contents to scale
vertically align text in a CATextLayer?
One thing I have tried in Swift is to set the following property:
textField.usesSingleLineMode = true
Any tips on the best way to vertically center text would be much appreciated!
This is very hard to do, as Apple makes this very difficult. I achieved it by subclassing NSTextFieldCell and overriding the drawingRectForBounds: method like so:
override func drawingRectForBounds(theRect: NSRect) -> NSRect {
let newRect = NSRect(x: 0, y: (theRect.size.height - 22) / 2, width: theRect.size.width, height: 22)
return super.drawingRectForBounds(newRect)
}
This is just my way to do it, I'm sure there are better ways, which I don't know (yet). And this only works for the standard font size in TextFields (which gives a text height of 22). That's why I hardcoded that. Haven't figured out yet, how to get the height in the cell if you change the font.
Result:
Try this on a playground, it centers the text perfectly, use it on your projects! Hope it helps!
import Cocoa
let cell = NSTableCellView()
cell.frame = NSRect(x: 0, y: 0, width: 100, height: 100)
let tf = NSTextField()
tf.frame = cell.frame
tf.stringValue = "MyTextfield"
tf.alignment = .Center
let stringHeight: CGFloat = tf.attributedStringValue.size().height
let frame = tf.frame
var titleRect: NSRect = tf.cell!.titleRectForBounds(frame)
titleRect.size.height = stringHeight + ( stringHeight - (tf.font!.ascender + tf.font!.descender ) )
titleRect.origin.y = frame.size.height / 2 - tf.lastBaselineOffsetFromBottom - tf.font!.xHeight / 2
tf.frame = titleRect
cell.addSubview(tf)
I have added the NSTextField inside a NSView and centered it.
Another solution was (in an iOS project) to create a UILabel and allow it adjust its size (sizeToFit()) and again embed it inside a UIView.
I personally don't like the calculations in previous answers and the second solution for iOS works for all texts size and row numbers.
I was also facing vertical alignment issue with NSTextField. My requirement involved, rendering a single-line string inside a NSTextField. Additionally,
textfield needed to be resize implying we had programatically resized the font-point-size of the text inside text-field on resize. In this scenario we faced vertical-alignment issues - the mis-alignment was tough to grasp/understand in a straight forward way.
What finally worked:
So, in my scenario a simple,
turn off the "Single Line Mode" in interface builder
for the text-field solved the issue.
The accepted answer works perfectly and here's the Swift3 version.
class VerticallyAlignedTextFieldCell: NSTextFieldCell {
override func drawingRect(forBounds rect: NSRect) -> NSRect {
let newRect = NSRect(x: 0, y: (rect.size.height - 22) / 2, width: rect.size.width, height: 22)
return super.drawingRect(forBounds: newRect)
}
}

NSAttributedString: image not showing up in UILabel

For some reason, the image does not display. I have dropped test.png and test#2x.png both under Image.xcassets/ I also dropped it within the project. None of that helped. Any assistance would be greatly appreciated.
var testView: UILabel = UILabel(frame: CGRectMake(20, 20, self.view.frame.width-40, self.view.frame.height-40))
var a = "Testing..."
var attachment = NSTextAttachment()
//This is the image that I would like to add
// I have dropped test.png and test#2x.png under Image.xcassets
attachment.image = UIImage(named: "test")
var attachmentString = NSAttributedString(attachment: attachment)
let attrsB = NSAttributedString(
string: "2nd line..Testing testing",
attributes: NSDictionary(
object: UIFont(name: "HelveticaNeue", size: 18.0)!,
forKey: NSFontAttributeName) as [NSObject : AnyObject])
a.appendAttributedString(attrsB)
let attributedTextToDisplay = NSMutableAttributedString(attributedString: a)
attributedTextToDisplay.appendAttributedString(attachmentString)
testView.attributedText = attributedTextToDisplay
self.view.addSubview(testView)
You need to allow your label to have multiple lines if you want to display more than 1 line.
var testView: UILabel = UILabel(frame: CGRectMake(20, 20, self.view.frame.width-40, self.view.frame.height-40))
testView.numberOfLines = 0;
Tips:
Use Storyboard & Interface Builder. WYSIWYG.
Use AutoLayout, it solves a lot of resizing for you
Use asserts if you are unsure of the content of a variable
Step into debugger and push on the eye icon to reveal quicklook
Eliminating all these variables will help you find out the root cause, and not worry, say, about whether or not your image is loaded. See sample below.
For good measures, I also explicitly typed a into a a:NSMutableAttributedString.
var a:NSMutableAttributedString
I had the issue when I used didSet {} on the IBOutlet, moving the code to ViewDidLoad() method solved it.