creating spaces in placeholder fields - ios

my problem is I want to put 2 placeholders for one textField. one of the place holders should be on the left and the other should be on the right.
my code:
func returnPlaceHolder(first: String, second: String, textField: UITextField){
let width: Int = Int(textField.bounds.width * 0.2)
let spaceValue = width - (first.count + second.count)
var temp = "\(first) "
let tempCount = spaceValue - (first.count + second.count)
var value = String()
for _ in 0..<tempCount {
temp.append(" ")
}
value = "\(temp) \(second)"
textField.placeholder = value
textField.setLeftPaddingPoints(10)
textField.setRightPaddingPoints(10)
}
I'm currently using this function to create spaces.. but my problem is the spaces won't be the same for more than one textField, and I want them to be aligned..
just like this picture: https://imgur.com/pZZMoNv
and this is the result I'm getting for my current code: https://imgur.com/a/5AN8EXl
don't mind the textFields format & text I can fix them later.. I just want to be able to align the textFields placeholders.

It would be really hard (if possible) to achieve what you are trying to do by injecting spaces into the text because each character in the font has a different width unless you use a monospaced font.
https://en.wikipedia.org/wiki/Monospaced_font
Instead, I would recommend a different approach. Override the text field, provide two UILabels and adjust their position using Autolayout.

Related

UITextView convertes three consecutive dots(...) into ellipses smaller dots(\u2026)

I am using UITextView and when user enter three consecutive dots ..., it gets replaced as ellipses … (unicode \u2026). How to avoid this? I need the actual string which user entered; not the auto corrected string.
Note: I have tried setting autoCorrectionType to .no, but no luck.
let textView = UITextView()
textView.delegate = self
textView.translatesAutoresizingMaskIntoConstraints = false
textView.font = UIFont.preferredFont(forTextStyle: .caption1)
Here is the delegate method,
func textViewDidChange(_ textView: UITextView) {
print("User entered string: \(textView.string)")
}
From Apple's docs:
Instance Property
smartDashesType
The configuration state for smart dashes.
Discussion
Use this property to configure whether UIKit converts two hyphens into an en-dash and three hyphens into an em-dash automatically. The default value of this property is UITextSmartDashesType.default, which selectively enables smart dashes based on the keyboard type.
Curiously, it makes no mention of converting three consecutive periods into an ellipses, but it IS part of that functionality.
So, using:
let textView = UITextView()
textView.smartDashesType = .no
will disable it -- but it will also disable the en-dash and em-dash conversion.

How to center justify text in UITextView?

I have an Arabic (right to left) text in textView, when I set myTextView.alignment = .justify, the last line in text go to the left side. How can I set center justify for textView or how can move last line to the center?
just make it .center
i know what exactly you're looking for cause i've been there before, only you can make it .center
Interesting question, I would try to count the lines in the textView and cut the last one than I would try to put the cut text in a new label below the textView ... ;)
after asking how I would do this I added this:
print(self.testLabel.frame.width)
self.testLabel.text = "Hello World"
self.testLabel.sizeToFit()
print(self.testLabel.frame.width)
This is a starting point you can work with. Create a label and set the width to zero. Insert your text and set sizeToFit(). Now you are able to get the length of the label. Is it to long for your view it will have more lines... (The divider is your length - not tested, maybe an offset is needed too)
The idea is now to subtract as long as your lines are more than one and the lines are the same amount at the beginning of your calculation to get the last word and put it at the beginning of a temp string.
If this returns you get your substring for the last line.
I was interested and started with this one:
#IBOutlet weak var textBox: UITextView!
#IBOutlet weak var testLabel: UILabel!
override func viewWillAppear(_ animated: Bool) {
print(self.testLabel.frame.width)
self.testLabel.text = self.textBox.text
self.testLabel.sizeToFit()
print("total \(self.testLabel.frame.width)")
let basicAmount = Int(self.testLabel.frame.width / self.textBox.frame.width) + 1
print("lines \(basicAmount)")
var lastLine: String = ""
while basicAmount == Int(self.testLabel.frame.width / self.textBox.frame.width) + 1 {
var arr = self.textBox.text.components(separatedBy: " ")
lastLine = "\(arr.last) \(lastLine)"
arr.removeLast()
self.textBox.text = arr.joined(separator: " ")
self.testLabel.text = self.textBox.text
self.testLabel.sizeToFit()
print(lastLine)
}
}
the interesting output is:
total 1499.5
lines 7
Optional("civiuda.")
Of course you should spent more time in the calculation because of the free space at the end of a line...
use this
self.textView.textAlignment = .justified //set text alignment center and justified
self.textView.makeTextWritingDirectionRightToLeft(true)//if you want set writing direction right to left
self.textView.makeTextWritingDirectionLeftToRight(true)//if you want set writing direction left to right

UITextField's width is never less than it's width with placeholder text

I have a UITextField and UILabel sitting together in a UIView as so:
and here it is in Xcode:
The label is hidden until the user enters some text into the text field, so it serves to provide a persistent "suffix" to the numeric entry. The problem is that when the user types a number into the text field, it doesn't shrink down to the size of the text, it remains at the size of the original placeholder, even though it isn't visible, as so:
Is there any way I can constrain the text field's width to be the minimum size to accommodate the user's text, and not pay attention to the invisible placeholder text's width?
Thank you
I managed to solve it myself:
Whenever the text is edited, the text field is checked to see if there is any text inside. If there is no text, the 'mg' suffix is hidden, and the placeholder is added. If there is text, the 'mg' suffix is shown and the placeholder is removed. Like so: (Swift)
func textFieldTextChanged(_ textField: UITextField) {
milligramTextField.invalidateIntrinsicContentSize()
view.layoutIfNeeded()
if textField.text == "" {
milligramSuffixLabel.text = ""
milligramTextField.placeholder = "0 mg"
} else {
milligramSuffixLabel.text = " mg"
milligramTextField.placeholder = ""
}
}
This answer was of great help.

Unicode non-breaking space is removed end of label

I'm using tableview and i use one cell to create many columns.My column number is not fixed so i had to create columns using for loop inside cellForRowAt function.I want to give some spaces between my labels inside my cell.This piece of code succesfully inserts non-breaking spaces to head of the label but it removes end of the label.Thanks for your help.
let spaces = String(repeating:"\u{00A0}",count : columnSpaceCount)
if globalSubviewHeaderStructArray[i].type == "numeric"{
if globalSubviewHeaderStructArray[i].digitsAfterComma != "0" {
var dataNumber = applyComma(comma : globalSubviewHeaderStructArray[i].digitsAfterComma , data : globalSubviewDataArray[indexPath.row][i])
var newString = "\(spaces)\(checkCurrency(option: globalSubviewHeaderStructArray[i].currency, data: dataNumber))\(spaces)"
newLabel.text = newString
}else{
var newString = "\(spaces)\(checkCurrency(option: globalSubviewHeaderStructArray[i].currency, data: globalSubviewDataArray[indexPath.row][i]))\(spaces)"
newLabel.text = newString
}
}else{
var newString = "\(spaces)\(checkCurrency(option: globalSubviewHeaderStructArray[i].currency, data: globalSubviewDataArray[indexPath.row][i]))\(spaces)"
newLabel.lineBreakMode = .byTruncatingMiddle
newLabel.text = newString
}
I want to give some spaces between my labels inside my cell
Don't do this by messing with the content of the label. Do it by messing with the position / size of the labels themselves. Insert actual space (that is, empty pixels) between the labels.
To insert space in between UILabels within a UITableViewCell, set up Autolayout Contraints, either in Storyboard or in code. Depending on the target iOS version, embedding the UILabels in a StackView is probably the easiest way, but it's available in iOS >= 8 only.
Select the labels:
Choose Embed in -> Stack View:
Set spacing:
Also set the contraints for the StackView to your needs:

Inset text in UILabel from left

I have a UILabel which I am using to display multiple lines of text. At the moment when the text is displayed, it is right up against the left hand side of the label which doesn't look too great. I would like the text to be inset slightly from the left.
This is my code so far:
if notes.objectAtIndex(indexPath.row) as NSString == "" {
cell.notesLabel.text = "No notes to display."
cell.notesLabel.textAlignment = NSTextAlignment.Center
} else {
cell.notesLabel.textAlignment = NSTextAlignment.Left
}
I was looking at some Objective-C examples but I couldn't get them to work and I don't really think they were what I was looking for.
Also, I was trying to do the same thing with a different label and in that case I assumed I could have just added " " to the end of the string (as it is a single line label) to move it in from the right, but I was surprised to see that this doesn't work?
Thanks.
To inset the text from the left edge, you should create a UILabel subclass, and override drawTextInRect:,
class RDLabel: UILabel {
override func drawTextInRect(rect: CGRect) {
let newRect = CGRectOffset(rect, 10, 0) // move text 10 points to the right
super.drawTextInRect(newRect)
}
}

Resources