How can I set the attributed text while having no placeholder text? - ios

Code that worked in Xcode 6.2 no longer works and I'm having trouble figuring out how to fix it. String attributes are now ignored unless I set default text. Here's what I've got right now:
let font = UIFont(name: "Arial-BoldMT", size: 42.0)!
let textStyle = NSMutableParagraphStyle.defaultParagraphStyle().mutableCopy() as! NSMutableParagraphStyle
textStyle.alignment = NSTextAlignment.Center
let textColor = UIColor.whiteColor()
var shadow = NSShadow()
shadow.shadowColor = UIColor.blackColor()
shadow.shadowOffset = CGSizeMake(2.0,2.0)
var attr = [String:NSObject]()
attr = [
NSFontAttributeName: font,
NSForegroundColorAttributeName: textColor,
NSParagraphStyleAttributeName: textStyle,
NSShadowAttributeName: shadow
]
let placeholderText = NSAttributedString(string: "", attributes: attr)
textView.attributedText = placeholderText

If you change the placeHolderText to NSAttributedString(string: " ", attributes: attr) you can then change the UITextView's text by changing its text property and the new text will have all the same attributes.
I hope that answers your question.

Related

UITextField Placeholder and Text Size should be separate - Swift

My requirement is such that when placeholder of textfield is visible then its color should be gray and font size 10, but when user starts typing into the textfield, its color should be black and font size 14. I have tried this:
textField.attributedPlaceholder = NSAttributedString(string: placeholderText,
attributes: [NSAttributedString.Key.foregroundColor: Color.iPhoneGrayColor, NSAttributedString.Key.font: UIFont(name: "SourceSansPro-Regular", size: 10)!])
textField.textColor = UIColor.black
textField.font = UIFont(name: "SourceSansPro-Regular", size: 14)!
But, my placeholder font size is getting overridden by textfield.font, so I am unable to get placeholder of size 10. Where am I going wrong? Tried this for couple of hours now. Any help will be appreciated.
Simply set the placeholder after setting the font since setting the font also applies to the placeholder (see https://developer.apple.com/documentation/uikit/uitextfield/1619604-font):
textField.font = ...
textField.textColor = ...
textField.attributedPlaceholder = ...
Try this code into your viewDidLoad() method:
textField.attributedPlaceholder = NSAttributedString(string: placeholderText, attributes: [NSAttributedString.Key.foregroundColor: Color.iPhoneGrayColor, NSAttributedString.Key.font: UIFont(name: "SourceSansPro-Regular", size: 10)!])
textField.textColor = UIColor.black
textField.font = UIFont(name: "SourceSansPro-Regular", size: 14)!
Just try this code, take the UITextFieldEditingChanged action outlet and use as below.
#IBAction func nameTextFieldEditingChanged(_ sender: UITextField) {
if sender.text?.isEmpty ?? true {
//placeholder text size set here
textField.font = UIFont(name: "SourceSansPro-Regular", size: 10)!
} else {
// When user starting typing
textField.textColor = UIColor.black
textField.font = UIFont(name: "SourceSansPro-Regular", size: 14)!
}
}
If any doubt please comment ].
Just try this code may help you for further:
var myMutableStringTitle = NSMutableAttributedString()
let Name = "Enter Title" // PlaceHolderText
myMutableStringTitle = NSMutableAttributedString(string:Name, attributes: [NSFontAttributeName:UIFont(name: "Georgia", size: 20.0)!]) // Font
myMutableStringTitle.addAttribute(NSForegroundColorAttributeName, value: UIColor.redColor(), range:NSRange(location:0,length:Name.characters.count)) // Color
txtTitle.attributedPlaceholder = myMutableStringTitle

How to color potion of an UILabel in swift 3

I want to achieve something like this without using 2 labels.
How can I create an UILabel like this.Please help me.
You can use the NSBackgroundColorAttributeName property of the NSMutableAttributedString to achieve the above result
var attributedString = NSMutableAttributedString(string:yourString)attributedString.addAttribute(NSBackgroundColorAttributeName, value: .redColor() , range: range)
yourLabel.attributedText = attributedString
For achieving this output we use NSAttribute class
Try below code
//This is for setting border of UILabel
let labelColor = UIColor(colorLiteralRed: 255.0/255.0, green: 115.0/255.0, blue: 116.0/255.0, alpha: 1.0)
lblNoOfDays.layer.masksToBounds = true
lblNoOfDays.layer.borderWidth = 1.0
lblNoOfDays.layer.borderColor = labelColor.cgColor
//This is value we display
let strValueTitle = "No of Days"
let strValue = "04"
//Attribute dictionary we use
//NSFontAttributeName:- sets font and it's size
//NSForegroundColorAttributeName:- sets text colour
//NSBackgroundColorAttributeName:- sets background color
let attributeTitle = [NSFontAttributeName: UIFont.systemFont(ofSize: 11.0), NSForegroundColorAttributeName: labelColor, NSBackgroundColorAttributeName: UIColor.clear]
let attributeVal = [NSFontAttributeName: UIFont.systemFont(ofSize: 12.0), NSForegroundColorAttributeName: UIColor.white, NSBackgroundColorAttributeName: labelColor]
//Implement attributes to string
let attributTitleString = NSMutableAttributedString(string: strValueTitle, attributes: attributeTitle)
let attributeValue = NSAttributedString(string: strValue, attributes: attributeVal)
//Append attributed string
attributTitleString.append(attributeValue)
//Assign attributed string to label
lblNoOfDays.attributedText = attributTitleString
lblNoOfDays.sizeToFit()
You need to set padding in UILabel for getting desired output.

How to center vertically attributed text (custom placeholder font) in UITextField?

I am using attributed text property to set custom placeholder font in UITExtfield. But my placeholder text is not vertically centered.Here is preview
let font = UIFont(name: Font.myFont.name, size: 15)!
let attributes = [
NSForegroundColorAttributeName: UIColor.cadetGrey,
NSFontAttributeName: font
]
exampleTextField.attributedPlaceholder = NSAttributedString(string: "Example Placeholder",
attributes: attributes)
I tried to add
let centeredParagraphStyle = NSMutableParagraphStyle()
centeredParagraphStyle.alignment = .center
to attribute still no luck. I also tried to use SizeToFit() on my UITextBox but no luck at all
This worked for me in Swift 5:
let unitText = NSAttributedString(string: "\(unit)", attributes: [NSAttributedString.Key.foregroundColor: MyColors.doveGray, NSAttributedString.Key.baselineOffset:2])
Try like this :
let centeredParagraphStyle = NSMutableParagraphStyle()
centeredParagraphStyle.alignment = .center
let attributes: [String : Any] = [NSParagraphStyleAttributeName: centeredParagraphStyle]
This is will set both placeholder and text input by user in center.
exampleTextField.textAlignment = .center
To center both vertically and horizontally.
exampleTextField.contentVerticalAlignment = UIControlContentVerticalAlignment.center
exampleTextField.textAlignment = .center
OR
This is will only set placeholder in center whereas the text input by user will remain at it's default position i.e left align
let font = UIFont(name: Font.myFont.name, size: 15)!
let centeredParagraphStyle = NSMutableParagraphStyle()
centeredParagraphStyle.alignment = .center
// add attribute of NSMutableParagraphStyle
let attributes = [
NSForegroundColorAttributeName: UIColor.gray,
NSFontAttributeName: font,
NSParagraphStyleAttributeName: centeredParagraphStyle
]
exampleTextField.attributedPlaceholder = NSAttributedString(string: "Example Placeholder",
attributes: attributes)

How to change UITextfield placeholder color and fontsize using swift 2.0?

How to change UITextfield placeholder & fontsize in SWIFT 2.0?
#1. set Placeholder textfield color Programmatically
var myMutableStringTitle = NSMutableAttributedString()
let Name = "Enter Title" // PlaceHolderText
myMutableStringTitle = NSMutableAttributedString(string:Name, attributes: [NSFontAttributeName:UIFont(name: "Georgia", size: 20.0)!]) // Font
myMutableStringTitle.addAttribute(NSForegroundColorAttributeName, value: UIColor.redColor(), range:NSRange(location:0,length:Name.characters.count)) // Color
txtTitle.attributedPlaceholder = myMutableStringTitle
OR
txtTitle.attributedPlaceholder = NSAttributedString(string:"Enter Title", attributes: [NSForegroundColorAttributeName: yellowColor])
Note : Name is your placeholder of textField.
PlaceHolder TextFiled :
-------------------------------- OR -------------------------------------
#2. set Placeholder textfield color at runtime attribute
Set textfield placeHolder text Enter Title
Click on identity inspector of textfield property.
User Define Runtime Attributes, add color attributes
Key Path : _placeholderLabel.textColor
Type : Color
value : Your Color or RGB value
PlaceHolder TextFiled :
Updated for Swift 3
If you want to change the UITextField Placeholder color for Swift 3, use the following lines of code:
let yourTextFieldName = UITextField(frame: CGRect(x: 0, y: 0, width: 180, height: 21))
yourTextFieldName.attributedPlaceholder = NSAttributedString(string: "placeholder text", attributes: [NSForegroundColorAttributeName: UIColor.white])
Updated for Swift 5
For swift 5.0 use NSAttributedString.Key.foregroundColor instead of NSForegroundColorAttributeName
So, do it like so
textField.attributedPlaceholder = NSAttributedString(string: "placeholder text", attributes: [NSAttributedString.Key.foregroundColor: UIColor.white])
For swift 4 instead of
NSForegroundColorAttributeName
use
NSAttributedStringKey.foregroundColor
You can try with this sample code
let textFld = UITextField();
textFld.frame = CGRectMake(0,0, 200, 30)
textFld.center = self.view.center;
textFld.attributedPlaceholder = NSAttributedString(string:"Test Data for place holder", attributes:[NSForegroundColorAttributeName: UIColor.blueColor(),NSFontAttributeName :UIFont(name: "Arial", size: 10)!])
self.view.addSubview(textFld)
Placeholder for textfield Objective C
NSString* str = #"Placeholder text...";
NSRange range1 = [str rangeOfString:#"Placeholder text..."];
NSMutableAttributedString *attributedText = [[NSMutableAttributedString alloc] initWithString:str];
[attributedText setAttributes:#{
NSFontAttributeName:[UIFont fontWithName:customFont_NotoSans_Regular size:13.0]
}
range:range1];
[attributedText addAttribute:NSForegroundColorAttributeName value:[UIColor whiteColor] range:range1];
txtFld.font = [UIFont fontWithName:customFont_NotoSans_Regular size:13.0];
txtFld.keyboardType = UIKeyboardTypeDefault;
txtFld.attributedPlaceholder = attributedText;
It's easy to do with a subclass of UITextField.
Add placeholderColor property to easily set the color, and then observer changing of .placeholder to apply the color to it (with use of .attributedPlaceholder property)
var placeholderColor: UIColor = .lightGray
override var placeholder: String? {
didSet {
let attributes = [ NSAttributedString.Key.foregroundColor: placeholderColor ]
attributedPlaceholder = NSAttributedString(string: placeholder ?? "", attributes: attributes)
}
}
You do need to set the placeholder text programatically for the color to apply.
set Textfield placeholder
let leftBarButtonItem = UIBarButtonItem.init(image: UIImage(named:"ic_nav-bar_back.png"), landscapeImagePhone: nil, style: .plain, target: viewController, action: #selector(viewController.buttonClick(_:)))
leftBarButtonItem.imageInsets = UIEdgeInsets(top: 0, left: -15, bottom: 0, right: 0)
leftBarButtonItem.tintColor = UIColor(hex: 0xED6E19)
viewController.navigationItem.setLeftBarButton(leftBarButtonItem, animated: true)
A simple solution is override placeholder property in an UITextField extension. It will update color of placeholder whole project. You don't need to update your code in many places.
extension UITextField {
var placeholder: String? {
get {
attributedPlaceholder?.string
}
set {
guard let newValue = newValue else {
attributedPlaceholder = nil
return
}
let attributes: [NSAttributedString.Key: Any] = [.foregroundColor: Color.textFieldPlaceholder.color]
let attributedText = NSAttributedString(string: newValue, attributes: attributes)
attributedPlaceholder = attributedText
}
}
}
open your identity inspector by selecting text field and then put " placeholderLabel.textColor " in key path by pressing + button .
Give the type " Color " and in value select desired RGB color.
Swift 5
textfiled.attributedPlaceholder = NSAttributedString(string:NSLocalizedString("Input Group Name", comment: "Input Group Name"), attributes: [NSAttributedString.Key.foregroundColor: yourColor.withAlphaComponent(0.5)])

How do you programmatically center the alignment of a text label for iOS?

I want to set the alignment of a text label, how can I do that?
I think there are the answers who helped you out. The correct way to do this is:
yourLabelName.textAlignment = NSTextAlignmentCenter;
for more documentation you can read this:
https://developer.apple.com/documentation/uikit/uilabel
In Swift :-
yourLabelName.textAlignment = .center
Here .center is NSTextAlignment.center
Here you are,
yourLabel.textAlignment = UITextAlignmentCenter
EDIT
if you target above iOS6 use NSTextAlignmentCenter as UITextAlignmentCenter is depreciated
Hope it helps.
This has changed as of iOS 6.0, UITextAlignment has been deprecated. The correct way to do this now is:
yourLabel.textAlignment = NSTextAlignmentCenter;
Here is the NSTextAlignment enumerable that gives the options for text alignment:
Objective-C:
enum {
NSTextAlignmentLeft = 0,
NSTextAlignmentCenter = 1,
NSTextAlignmentRight = 2,
NSTextAlignmentJustified = 3,
NSTextAlignmentNatural = 4,
};
typedef NSInteger NSTextAlignment;
Swift:
enum NSTextAlignment : Int {
case Left
case Center
case Right
case Justified
case Natural
}
Source
label.textAlignment = NSTextAlignmentCenter;
see UILabel documentation
If you have a multiline UILabel you should use a NSMutableParagraphStyle
yourLabelName.numberOfLines = 0
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.alignment = .Center
let attributes : [String : AnyObject] = [NSFontAttributeName : UIFont(name: "HelveticaNeue", size: 15)!, NSParagraphStyleAttributeName: paragraphStyle]
let attributedText = NSAttributedString.init(string: subTitleText, attributes: attributes)
yourLabelName.attributedText = attributedText
In Swift 3 and beyond it should be
yourlabel.textAlignment = NSTextAlignment.center
in swift 4:
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.alignment = NSTextAlignment.center
// in Swift 4.2
let attributedString = NSMutableAttributedString(string: "Your String", attributes:[NSAttributedString.Key.paragraphStyle:paragraphStyle])
// in Swift 4.1--
let attributedString = NSMutableAttributedString(string: "Your String", attributes: [NSAttributedStringKey.paragraphStyle:paragraphStyle])
let yourLabel = UILabel()
yourLabel.attributedText = attributedString
Yourlabel.textAlignment = UITextAlignmentCenter;

Resources