How to add "Copy" option to text? - ios

I have a text in a "bubble" by fitting the text inside an image as shown below. it works fine except the text is not copyable. I need to have "copy" option so that when user tab on the text (or bubble image") "cop" options is displayed, just like in when user tab into the built in SMS Message bubble.
#import "SpeechBubbleView.h"
static UIFont* font = nil;
static UIImage* lefthandImage = nil;
static UIImage* righthandImage = nil;
const CGFloat VertPadding = 4; // additional padding around the edges
const CGFloat HorzPadding = 4;
const CGFloat TextLeftMargin = 17; // insets for the text
const CGFloat TextRightMargin = 15;
const CGFloat TextTopMargin = 10;
const CGFloat TextBottomMargin = 11;
const CGFloat MinBubbleWidth = 50; // minimum width of the bubble
const CGFloat MinBubbleHeight = 40; // minimum height of the bubble
const CGFloat WrapWidth = 200; // maximum width of text in the bubble
#implementation SpeechBubbleView
+ (void)initialize
{
if (self == [SpeechBubbleView class])
{
font = /*[*/ [UIFont systemFontOfSize:[UIFont systemFontSize]] /*retain]*/;
lefthandImage = /*[*/ [[UIImage imageNamed:/*#"BubbleLefthand"*/#"lefttest4"]
stretchableImageWithLeftCapWidth:20 topCapHeight:19] /*retain]*/;
righthandImage = /*[*/[[UIImage imageNamed:/*#"BubbleRighthand"*/#"righttest4"]
stretchableImageWithLeftCapWidth:20 topCapHeight:19] /*retain]*/;
}
}
+ (CGSize)sizeForText:(NSString*)text
{
CGSize textSize = [text sizeWithFont:font
constrainedToSize:CGSizeMake(WrapWidth, 9999)
lineBreakMode:UILineBreakModeWordWrap];
CGSize bubbleSize;
bubbleSize.width = textSize.width + TextLeftMargin + TextRightMargin;
bubbleSize.height = textSize.height + TextTopMargin + TextBottomMargin;
if (bubbleSize.width < MinBubbleWidth)
bubbleSize.width = MinBubbleWidth;
if (bubbleSize.height < MinBubbleHeight)
bubbleSize.height = MinBubbleHeight;
bubbleSize.width += HorzPadding*2;
bubbleSize.height += VertPadding*2;
return bubbleSize;
}
- (void)drawRect:(CGRect)rect
{
[self.backgroundColor setFill];
UIRectFill(rect);
CGRect bubbleRect = CGRectInset(self.bounds, VertPadding, HorzPadding);
CGRect textRect;
textRect.origin.y = bubbleRect.origin.y + TextTopMargin;
textRect.size.width = bubbleRect.size.width - TextLeftMargin - TextRightMargin;
textRect.size.height = bubbleRect.size.height - TextTopMargin - TextBottomMargin;
if (bubbleType == BubbleTypeLefthand)
{
[lefthandImage drawInRect:bubbleRect];
textRect.origin.x = bubbleRect.origin.x + TextLeftMargin;
}
else
{
[righthandImage drawInRect:bubbleRect];
textRect.origin.x = bubbleRect.origin.x + TextRightMargin;
}
[[UIColor blackColor] set];
[text drawInRect:textRect withFont:font lineBreakMode:UILineBreakModeWordWrap];
}
- (void)setText:(NSString*)newText bubbleType:(BubbleType)newBubbleType
{
//[text release];
/**
handle local
**/
// text = [newText copy];
text = [newText copy];
bubbleType = newBubbleType;
[self setNeedsDisplay];
}
- (void)dealloc
{
//[text release];
//[super dealloc];
}
#end

If you want the system cut/copy/paste menu (or some subset thereof) without the full suite of text editability features from UITextField or UITextView, you need to present your own UIMenuController. Doing this requires:
the control to be affected by the menu can become first responder
said control (or something sensible in the responder chain above it) implements the editing methods (e.g. copy:) you want to support
you perform some event handling to present the menu controller at an appropriate time (e.g. a gesture recognizer action)
As is often the case, there's a good tutorial on NSHipster with both Swift and ObjC sample code. Kudos to #mattt, though I'd say this line needs a correction:
If you’re wondering why, oh why, this isn’t just built into UILabel, well… join the club.
"Join the club" should be replaced with "file a bug". It even sorta almost rhymes!

Related

Fit background color to special characters [duplicate]

I have a UILabel with space for two lines of text. Sometimes, when the text is too short, this text is displayed in the vertical center of the label.
How do I vertically align the text to always be at the top of the UILabel?
There's no way to set the vertical-align on a UILabel, but you can get the same effect by changing the label's frame. I've made my labels orange so you can see clearly what's happening.
Here's the quick and easy way to do this:
[myLabel sizeToFit];
If you have a label with longer text that will make more than one line, set numberOfLines to 0 (zero here means an unlimited number of lines).
myLabel.numberOfLines = 0;
[myLabel sizeToFit];
Longer Version
I'll make my label in code so that you can see what's going on. You can set up most of this in Interface Builder too. My setup is a View-Based App with a background image I made in Photoshop to show margins (20 points). The label is an attractive orange color so you can see what's going on with the dimensions.
- (void)viewDidLoad
{
[super viewDidLoad];
// 20 point top and left margin. Sized to leave 20 pt at right.
CGRect labelFrame = CGRectMake(20, 20, 280, 150);
UILabel *myLabel = [[UILabel alloc] initWithFrame:labelFrame];
[myLabel setBackgroundColor:[UIColor orangeColor]];
NSString *labelText = #"I am the very model of a modern Major-General, I've information vegetable, animal, and mineral";
[myLabel setText:labelText];
// Tell the label to use an unlimited number of lines
[myLabel setNumberOfLines:0];
[myLabel sizeToFit];
[self.view addSubview:myLabel];
}
Some limitations of using sizeToFit come into play with center- or right-aligned text. Here's what happens:
// myLabel.textAlignment = NSTextAlignmentRight;
myLabel.textAlignment = NSTextAlignmentCenter;
[myLabel setNumberOfLines:0];
[myLabel sizeToFit];
The label is still sized with a fixed top-left corner. You can save the original label's width in a variable and set it after sizeToFit, or give it a fixed width to counter these problems:
myLabel.textAlignment = NSTextAlignmentCenter;
[myLabel setNumberOfLines:0];
[myLabel sizeToFit];
CGRect myFrame = myLabel.frame;
// Resize the frame's width to 280 (320 - margins)
// width could also be myOriginalLabelFrame.size.width
myFrame = CGRectMake(myFrame.origin.x, myFrame.origin.y, 280, myFrame.size.height);
myLabel.frame = myFrame;
Note that sizeToFit will respect your initial label's minimum width. If you start with a label 100 wide and call sizeToFit on it, it will give you back a (possibly very tall) label with 100 (or a little less) width. You might want to set your label to the minimum width you want before resizing.
Some other things to note:
Whether lineBreakMode is respected depends on how it's set. NSLineBreakByTruncatingTail (the default) is ignored after sizeToFit, as are the other two truncation modes (head and middle). NSLineBreakByClipping is also ignored. NSLineBreakByCharWrapping works as usual. The frame width is still narrowed to fit to the rightmost letter.
Mark Amery gave a fix for NIBs and Storyboards using Auto Layout in the comments:
If your label is included in a nib or storyboard as a subview of the view of a ViewController that uses autolayout, then putting your sizeToFit call into viewDidLoad won't work, because autolayout sizes and positions the subviews after viewDidLoad is called and will immediately undo the effects of your sizeToFit call. However, calling sizeToFit from within viewDidLayoutSubviews will work.
My Original Answer (for posterity/reference):
This uses the NSString method sizeWithFont:constrainedToSize:lineBreakMode: to calculate the frame height needed to fit a string, then sets the origin and width.
Resize the frame for the label using the text you want to insert. That way you can accommodate any number of lines.
CGSize maximumSize = CGSizeMake(300, 9999);
NSString *dateString = #"The date today is January 1st, 1999";
UIFont *dateFont = [UIFont fontWithName:#"Helvetica" size:14];
CGSize dateStringSize = [dateString sizeWithFont:dateFont
constrainedToSize:maximumSize
lineBreakMode:self.dateLabel.lineBreakMode];
CGRect dateFrame = CGRectMake(10, 10, 300, dateStringSize.height);
self.dateLabel.frame = dateFrame;
Set the new text:
myLabel.text = #"Some Text"
Set the maximum number of lines to 0 (automatic):
myLabel.numberOfLines = 0
Set the frame of the label to the maximum size:
myLabel.frame = CGRectMake(20,20,200,800)
Call sizeToFit to reduce the frame size so the contents just fit:
[myLabel sizeToFit]
The labels frame is now just high and wide enough to fit your text. The top left should be unchanged. I have tested this only with the top left-aligned text. For other alignments, you might have to modify the frame afterward.
Also, my label has word wrapping enabled.
Refering to the extension solution:
for(int i=1; i< newLinesToPad; i++)
self.text = [self.text stringByAppendingString:#"\n"];
should be replaced by
for(int i=0; i<newLinesToPad; i++)
self.text = [self.text stringByAppendingString:#"\n "];
Additional space is needed in every added newline, because iPhone UILabels' trailing carriage returns seems to be ignored :(
Similarly, alignBottom should be updated too with a #" \n#%" in place of "\n#%" (for cycle initialization must be replaced by "for(int i=0..." too).
The following extension works for me:
// -- file: UILabel+VerticalAlign.h
#pragma mark VerticalAlign
#interface UILabel (VerticalAlign)
- (void)alignTop;
- (void)alignBottom;
#end
// -- file: UILabel+VerticalAlign.m
#implementation UILabel (VerticalAlign)
- (void)alignTop {
CGSize fontSize = [self.text sizeWithFont:self.font];
double finalHeight = fontSize.height * self.numberOfLines;
double finalWidth = self.frame.size.width; //expected width of label
CGSize theStringSize = [self.text sizeWithFont:self.font constrainedToSize:CGSizeMake(finalWidth, finalHeight) lineBreakMode:self.lineBreakMode];
int newLinesToPad = (finalHeight - theStringSize.height) / fontSize.height;
for(int i=0; i<newLinesToPad; i++)
self.text = [self.text stringByAppendingString:#"\n "];
}
- (void)alignBottom {
CGSize fontSize = [self.text sizeWithFont:self.font];
double finalHeight = fontSize.height * self.numberOfLines;
double finalWidth = self.frame.size.width; //expected width of label
CGSize theStringSize = [self.text sizeWithFont:self.font constrainedToSize:CGSizeMake(finalWidth, finalHeight) lineBreakMode:self.lineBreakMode];
int newLinesToPad = (finalHeight - theStringSize.height) / fontSize.height;
for(int i=0; i<newLinesToPad; i++)
self.text = [NSString stringWithFormat:#" \n%#",self.text];
}
#end
Then call [yourLabel alignTop]; or [yourLabel alignBottom]; after each yourLabel text assignment.
Just in case it's of any help to anyone, I had the same problem but was able to solve the issue simply by switching from using UILabel to using UITextView. I appreciate this isn't for everyone because the functionality is a bit different.
If you do switch to using UITextView, you can turn off all the Scroll View properties as well as User Interaction Enabled... This will force it to act more like a label.
No muss, no fuss
#interface MFTopAlignedLabel : UILabel
#end
#implementation MFTopAlignedLabel
- (void)drawTextInRect:(CGRect) rect
{
NSAttributedString *attributedText = [[NSAttributedString alloc] initWithString:self.text attributes:#{NSFontAttributeName:self.font}];
rect.size.height = [attributedText boundingRectWithSize:rect.size
options:NSStringDrawingUsesLineFragmentOrigin
context:nil].size.height;
if (self.numberOfLines != 0) {
rect.size.height = MIN(rect.size.height, self.numberOfLines * self.font.lineHeight);
}
[super drawTextInRect:rect];
}
#end
No muss, no Objective-c, no fuss but Swift 3:
class VerticalTopAlignLabel: UILabel {
override func drawText(in rect:CGRect) {
guard let labelText = text else { return super.drawText(in: rect) }
let attributedText = NSAttributedString(string: labelText, attributes: [NSFontAttributeName: font])
var newRect = rect
newRect.size.height = attributedText.boundingRect(with: rect.size, options: .usesLineFragmentOrigin, context: nil).size.height
if numberOfLines != 0 {
newRect.size.height = min(newRect.size.height, CGFloat(numberOfLines) * font.lineHeight)
}
super.drawText(in: newRect)
}
}
Swift 4.2
class VerticalTopAlignLabel: UILabel {
override func drawText(in rect:CGRect) {
guard let labelText = text else { return super.drawText(in: rect) }
let attributedText = NSAttributedString(string: labelText, attributes: [NSAttributedString.Key.font: font])
var newRect = rect
newRect.size.height = attributedText.boundingRect(with: rect.size, options: .usesLineFragmentOrigin, context: nil).size.height
if numberOfLines != 0 {
newRect.size.height = min(newRect.size.height, CGFloat(numberOfLines) * font.lineHeight)
}
super.drawText(in: newRect)
}
}
Easiest approach using Storyboard:
Embed Label in a StackView and set the following two attributes of StackView in the Attribute Inspector:
1- Axis to Horizontal,
2- Alignment to Top
Like the answer above, but it wasn't quite right, or easy to slap into code so I cleaned it up a bit. Add this extension either to it's own .h and .m file or just paste right above the implementation you intend to use it:
#pragma mark VerticalAlign
#interface UILabel (VerticalAlign)
- (void)alignTop;
- (void)alignBottom;
#end
#implementation UILabel (VerticalAlign)
- (void)alignTop
{
CGSize fontSize = [self.text sizeWithFont:self.font];
double finalHeight = fontSize.height * self.numberOfLines;
double finalWidth = self.frame.size.width; //expected width of label
CGSize theStringSize = [self.text sizeWithFont:self.font constrainedToSize:CGSizeMake(finalWidth, finalHeight) lineBreakMode:self.lineBreakMode];
int newLinesToPad = (finalHeight - theStringSize.height) / fontSize.height;
for(int i=0; i<= newLinesToPad; i++)
{
self.text = [self.text stringByAppendingString:#" \n"];
}
}
- (void)alignBottom
{
CGSize fontSize = [self.text sizeWithFont:self.font];
double finalHeight = fontSize.height * self.numberOfLines;
double finalWidth = self.frame.size.width; //expected width of label
CGSize theStringSize = [self.text sizeWithFont:self.font constrainedToSize:CGSizeMake(finalWidth, finalHeight) lineBreakMode:self.lineBreakMode];
int newLinesToPad = (finalHeight - theStringSize.height) / fontSize.height;
for(int i=0; i< newLinesToPad; i++)
{
self.text = [NSString stringWithFormat:#" \n%#",self.text];
}
}
#end
And then to use, put your text into the label, and then call the appropriate method to align it:
[myLabel alignTop];
or
[myLabel alignBottom];
An even quicker (and dirtier) way to accomplish this is by setting the UILabel's line break mode to "Clip" and adding a fixed amount of newlines.
myLabel.lineBreakMode = UILineBreakModeClip;
myLabel.text = [displayString stringByAppendingString:"\n\n\n\n"];
This solution won't work for everyone -- in particular, if you still want to show "..." at the end of your string if it exceeds the number of lines you're showing, you'll need to use one of the longer bits of code -- but for a lot of cases this'll get you what you need.
Instead of UILabel you may use UITextField which has vertical alignment option:
textField.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
textField.userInteractionEnabled = NO; // Don't allow interaction
I've struggled with this one for a long time and I wanted to share my solution.
This will give you a UILabel that will autoshrink text down to 0.5 scales and vertically center the text. These options are also available in Storyboard/IB.
[labelObject setMinimumScaleFactor:0.5];
[labelObject setBaselineAdjustment:UIBaselineAdjustmentAlignCenters];
Create a new class
LabelTopAlign
.h file
#import <UIKit/UIKit.h>
#interface KwLabelTopAlign : UILabel {
}
#end
.m file
#import "KwLabelTopAlign.h"
#implementation KwLabelTopAlign
- (void)drawTextInRect:(CGRect)rect {
int lineHeight = [#"IglL" sizeWithFont:self.font constrainedToSize:CGSizeMake(rect.size.width, 9999.0f)].height;
if(rect.size.height >= lineHeight) {
int textHeight = [self.text sizeWithFont:self.font constrainedToSize:CGSizeMake(rect.size.width, rect.size.height)].height;
int yMax = textHeight;
if (self.numberOfLines > 0) {
yMax = MIN(lineHeight*self.numberOfLines, yMax);
}
[super drawTextInRect:CGRectMake(rect.origin.x, rect.origin.y, rect.size.width, yMax)];
}
}
#end
Edit
Here's a simpler implementation that does the same:
#import "KwLabelTopAlign.h"
#implementation KwLabelTopAlign
- (void)drawTextInRect:(CGRect)rect
{
CGFloat height = [self.text sizeWithFont:self.font
constrainedToSize:rect.size
lineBreakMode:self.lineBreakMode].height;
if (self.numberOfLines != 0) {
height = MIN(height, self.font.lineHeight * self.numberOfLines);
}
rect.size.height = MIN(rect.size.height, height);
[super drawTextInRect:rect];
}
#end
In Interface Builder
Set UILabel to size of biggest possible Text
Set Lines to '0' in Attributes Inspector
In your code
Set the text of the label
Call sizeToFit on your label
Code Snippet:
self.myLabel.text = #"Short Title";
[self.myLabel sizeToFit];
For Adaptive UI(iOS8 or after) , Vertical Alignment of UILabel is to be set from StoryBoard by Changing the properties
noOfLines=0` and
Constraints
Adjusting UILabel LefMargin, RightMargin and Top Margin Constraints.
Change Content Compression Resistance Priority For Vertical=1000` So that Vertical>Horizontal .
Edited:
noOfLines=0
and the following constraints are enough to achieve the desired results.
Create a subclass of UILabel. Works like a charm:
// TopLeftLabel.h
#import <Foundation/Foundation.h>
#interface TopLeftLabel : UILabel
{
}
#end
// TopLeftLabel.m
#import "TopLeftLabel.h"
#implementation TopLeftLabel
- (id)initWithFrame:(CGRect)frame
{
return [super initWithFrame:frame];
}
- (CGRect)textRectForBounds:(CGRect)bounds limitedToNumberOfLines:(NSInteger)numberOfLines
{
CGRect textRect = [super textRectForBounds:bounds limitedToNumberOfLines:numberOfLines];
textRect.origin.y = bounds.origin.y;
return textRect;
}
-(void)drawTextInRect:(CGRect)requestedRect
{
CGRect actualRect = [self textRectForBounds:requestedRect limitedToNumberOfLines:self.numberOfLines];
[super drawTextInRect:actualRect];
}
#end
As discussed here.
What I did in my app was to set the UILabel's line property to 0 as well as to create a bottom constraint of the UILabel and make sure it is being set to >= 0 as shown in the image below.
Use textRect(forBounds:limitedToNumberOfLines:).
class TopAlignedLabel: UILabel {
override func drawText(in rect: CGRect) {
let textRect = super.textRect(forBounds: bounds, limitedToNumberOfLines: numberOfLines)
super.drawText(in: textRect)
}
}
I wrote a util function to achieve this purpose. You can take a look:
// adjust the height of a multi-line label to make it align vertical with top
+ (void) alignLabelWithTop:(UILabel *)label {
CGSize maxSize = CGSizeMake(label.frame.size.width, 999);
label.adjustsFontSizeToFitWidth = NO;
// get actual height
CGSize actualSize = [label.text sizeWithFont:label.font constrainedToSize:maxSize lineBreakMode:label.lineBreakMode];
CGRect rect = label.frame;
rect.size.height = actualSize.height;
label.frame = rect;
}
.How to use? (If lblHello is created by Interface builder, so I skip some UILabel attributes detail)
lblHello.text = #"Hello World! Hello World! Hello World! Hello World! Hello World! Hello World! Hello World! Hello World!";
lblHello.numberOfLines = 5;
[Utils alignLabelWithTop:lblHello];
I also wrote it on my blog as an article:
http://fstoke.me/blog/?p=2819
I took a while to read the code, as well as the code in the introduced page, and found that they all try to modify the frame size of label, so that the default center vertical alignment would not appear.
However, in some cases we do want the label to occupy all those spaces, even if the label does have so much text (e.g. multiple rows with equal height).
Here, I used an alternative way to solve it, by simply pad newlines to the end of label (pls note that I actually inherited the UILabel, but it is not necessary):
CGSize fontSize = [self.text sizeWithFont:self.font];
finalHeight = fontSize.height * self.numberOfLines;
finalWidth = size.width; //expected width of label
CGSize theStringSize = [self.text sizeWithFont:self.font constrainedToSize:CGSizeMake(finalWidth, finalHeight) lineBreakMode:self.lineBreakMode];
int newLinesToPad = (finalHeight - theStringSize.height) / fontSize.height;
for(int i = 0; i < newLinesToPad; i++)
{
self.text = [self.text stringByAppendingString:#"\n "];
}
I took the suggestions here and created a view which can wrap a UILabel and will size it and set the number of lines so that it is top aligned. Simply put a UILabel as a subview:
#interface TopAlignedLabelContainer : UIView
{
}
#end
#implementation TopAlignedLabelContainer
- (void)layoutSubviews
{
CGRect bounds = self.bounds;
for (UILabel *label in [self subviews])
{
if ([label isKindOfClass:[UILabel class]])
{
CGSize fontSize = [label.text sizeWithFont:label.font];
CGSize textSize = [label.text sizeWithFont:label.font
constrainedToSize:bounds.size
lineBreakMode:label.lineBreakMode];
label.numberOfLines = textSize.height / fontSize.height;
label.frame = CGRectMake(0, 0, textSize.width,
fontSize.height * label.numberOfLines);
}
}
}
#end
You can use TTTAttributedLabel, it supports vertical alignment.
#property (nonatomic) TTTAttributedLabel* label;
<...>
//view's or viewController's init method
_label.verticalAlignment = TTTAttributedLabelVerticalAlignmentTop;
I've found the answers on this question are now a bit out-of-date, so adding this for the auto layout fans out there.
Auto layout makes this issue pretty trivial. Assuming we're adding the label to UIView *view, the following code will accomplish this:
UILabel *label = [[UILabel alloc] initWithFrame:CGRectZero];
[label setText:#"Some text here"];
[label setTranslatesAutoresizingMaskIntoConstraints:NO];
[view addSubview:label];
[view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:#"H:|[label]|" options:0 metrics:nil views:#{#"label": label}]];
[view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:#"V:|[label]" options:0 metrics:nil views:#{#"label": label}]];
The label's height will be calculated automatically (using it's intrinsicContentSize) and the label will be positioned edge-to-edge horizontally, at the top of the view.
I've used a lot of the methods above, and just want to add a quick-and-dirty approach I've used:
myLabel.text = [NSString stringWithFormat:#"%#\n\n\n\n\n\n\n\n\n",#"My label text string"];
Make sure the number of newlines in the string will cause any text to fill the available vertical space, and set the UILabel to truncate any overflowing text.
Because sometimes good enough is good enough.
I wanted to have a label which was able to have multi-lines, a minimum font size, and centred both horizontally and vertically in it's parent view. I added my label programmatically to my view:
- (void) customInit {
// Setup label
self.label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, self.frame.size.width, self.frame.size.height)];
self.label.numberOfLines = 0;
self.label.lineBreakMode = UILineBreakModeWordWrap;
self.label.textAlignment = UITextAlignmentCenter;
// Add the label as a subview
self.autoresizesSubviews = YES;
[self addSubview:self.label];
}
And then when I wanted to change the text of my label...
- (void) updateDisplay:(NSString *)text {
if (![text isEqualToString:self.label.text]) {
// Calculate the font size to use (save to label's font)
CGSize textConstrainedSize = CGSizeMake(self.frame.size.width, INT_MAX);
self.label.font = [UIFont systemFontOfSize:TICKER_FONT_SIZE];
CGSize textSize = [text sizeWithFont:self.label.font constrainedToSize:textConstrainedSize];
while (textSize.height > self.frame.size.height && self.label.font.pointSize > TICKER_MINIMUM_FONT_SIZE) {
self.label.font = [UIFont systemFontOfSize:self.label.font.pointSize-1];
textSize = [ticker.blurb sizeWithFont:self.label.font constrainedToSize:textConstrainedSize];
}
// In cases where the frame is still too large (when we're exceeding minimum font size),
// use the views size
if (textSize.height > self.frame.size.height) {
textSize = [text sizeWithFont:self.label.font constrainedToSize:self.frame.size];
}
// Draw
self.label.frame = CGRectMake(0, self.frame.size.height/2 - textSize.height/2, self.frame.size.width, textSize.height);
self.label.text = text;
}
[self setNeedsDisplay];
}
Hope that helps someone!
FXLabel (on github) does this out of the box by setting label.contentMode to UIViewContentModeTop. This component is not made by me, but it is a component I use frequently and has tons of features, and seems to work well.
for anyone reading this because the text inside your label is not vertically centered, keep in mind that some font types are not designed equally. for example, if you create a label with zapfino size 16, you will see the text is not perfectly centered vertically.
however, working with helvetica will vertically center your text.
Subclass UILabel and constrain the drawing rectangle, like this:
- (void)drawTextInRect:(CGRect)rect
{
CGSize sizeThatFits = [self sizeThatFits:rect.size];
rect.size.height = MIN(rect.size.height, sizeThatFits.height);
[super drawTextInRect:rect];
}
I tried the solution involving newline padding and ran into incorrect behavior in some cases. In my experience, it's easier to constrain the drawing rect as above than mess with numberOfLines.
P.S. You can imagine easily supporting UIViewContentMode this way:
- (void)drawTextInRect:(CGRect)rect
{
CGSize sizeThatFits = [self sizeThatFits:rect.size];
if (self.contentMode == UIViewContentModeTop) {
rect.size.height = MIN(rect.size.height, sizeThatFits.height);
}
else if (self.contentMode == UIViewContentModeBottom) {
rect.origin.y = MAX(0, rect.size.height - sizeThatFits.height);
rect.size.height = MIN(rect.size.height, sizeThatFits.height);
}
[super drawTextInRect:rect];
}
If you are using autolayout, set the vertical contentHuggingPriority to 1000, either in code or IB. In IB you may then have to remove a height constraint by setting it's priority to 1 and then deleting it.
As long as you are not doing any complex task, you can use UITextView instead of UILabels.
Disable the scroll.
If you want the text to be displayed completely just user sizeToFit and sizeThatFits: methods
In swift,
let myLabel : UILabel!
To make your text of your Label to fit to screen and it's on the top
myLabel.sizeToFit()
To make your font of label to fit to the width of screen or specific width size.
myLabel.adjustsFontSizeToFitWidth = YES
and some textAlignment for label :
myLabel.textAlignment = .center
myLabel.textAlignment = .left
myLabel.textAlignment = .right
myLabel.textAlignment = .Natural
myLabel.textAlignment = .Justified
This is an old solution, use the autolayout on iOS >= 6
My solution:
Split lines by myself (ignoring label wrap settings)
Draw lines by myself (ignoring label alignment)
#interface UITopAlignedLabel : UILabel
#end
#implementation UITopAlignedLabel
#pragma mark Instance methods
- (NSArray*)splitTextToLines:(NSUInteger)maxLines {
float width = self.frame.size.width;
NSArray* words = [self.text componentsSeparatedByCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
NSMutableArray* lines = [NSMutableArray array];
NSMutableString* buffer = [NSMutableString string];
NSMutableString* currentLine = [NSMutableString string];
for (NSString* word in words) {
if ([buffer length] > 0) {
[buffer appendString:#" "];
}
[buffer appendString:word];
if (maxLines > 0 && [lines count] == maxLines - 1) {
[currentLine setString:buffer];
continue;
}
float bufferWidth = [buffer sizeWithFont:self.font].width;
if (bufferWidth < width) {
[currentLine setString:buffer];
}
else {
[lines addObject:[NSString stringWithString:currentLine]];
[buffer setString:word];
[currentLine setString:buffer];
}
}
if ([currentLine length] > 0) {
[lines addObject:[NSString stringWithString:currentLine]];
}
return lines;
}
- (void)drawRect:(CGRect)rect {
if ([self.text length] == 0) {
return;
}
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetFillColorWithColor(context, self.textColor.CGColor);
CGContextSetShadowWithColor(context, self.shadowOffset, 0.0f, self.shadowColor.CGColor);
NSArray* lines = [self splitTextToLines:self.numberOfLines];
NSUInteger numLines = [lines count];
CGSize size = self.frame.size;
CGPoint origin = CGPointMake(0.0f, 0.0f);
for (NSUInteger i = 0; i < numLines; i++) {
NSString* line = [lines objectAtIndex:i];
if (i == numLines - 1) {
[line drawAtPoint:origin forWidth:size.width withFont:self.font lineBreakMode:UILineBreakModeTailTruncation];
}
else {
[line drawAtPoint:origin forWidth:size.width withFont:self.font lineBreakMode:UILineBreakModeClip];
}
origin.y += self.font.lineHeight;
if (origin.y >= size.height) {
return;
}
}
}
#end

Add padding around ASTextNode

I am working with AsyncDisplayKit (for the first time) and have an ASTextNode inside a ASCellNode. I want to adding padding or an inset around the text inside the ASTextNode. I attempted to wrap it with a ASDisplayNode but whenever I calculated it's size in calculateSizeThatFits: it always returned 0. Any suggestions would be appreciated. The code that is in the ASCellNode subclass is:
- (CGSize)calculateSizeThatFits:(CGSize)constrainedSize
{
CGSize textSize = [self.commentNode measure:CGSizeMake(constrainedSize.width - kImageSize - kImageToCommentPadding - kCellPadding - kInnerPadding, constrainedSize.height)];
return CGSizeMake(constrainedSize.width, textSize.height);
}
- (void)layout
{
self.imageNode.frame = CGRectMake(kCellPadding, kCellPadding, kImageSize, kImageSize);
self.imageNode.layer.cornerRadius = kImageSize / 2.f;
self.imageNode.layer.masksToBounds = YES;
self.imageNode.layer.borderColor = [UIColor whiteColor].CGColor;
self.imageNode.layer.borderWidth = 2.f;
self.commentNode.backgroundColor = [UIColor whiteColor];
self.commentNode.layer.cornerRadius = 8.f;
self.commentNode.layer.masksToBounds = YES;
CGSize textSize = self.commentNode.calculatedSize;
self.commentNode.frame = CGRectMake(kCellPadding + kImageSize + kCellPadding, kCellPadding, textSize.width, textSize.height);
}
If you node is returning 0 height / size, you may be forgetting to invalidate its current size after changing its content.
Use: [node invalidateCalculatedSize];
For padding around the text node, you could add a node behind it with the size you want and then set a hitTestSlop on the text node.
This would increase its tappable area.
The better approach might be to embed it inside a custom node e.g.
Interface
#interface InsetTextNode: ASControlNode
#property (nonatomic) UIEdgeInsets textInsets;
#property (nonatomic) NSAttributedString * attributedString;
#property ASTextNode * textNode;
#end
Implementation
#implementation InsetTextNode
- (instancetype)init
{
self = [super init];
if (!self) return nil;
[self addSubnode:textNode];
self.textInsets = UIEdgeInsetsMake(8, 16, 8, 16);
return self;
}
- (CGSize)calculateSizeThatFits:(CGSize)constrainedSize
{
CGFloat availableTextWidth = constrainedSize.width - self.textInsets.left - self.textInsets.right;
CGFloat availableTextHeight = constrainedSize.height - self.textInsets.top - self.textInsets.bottom;
CGSize constrainedTextSize = CGSizeMake(availableTextWidth, availableTextHeight);
CGSize textSize = [self.textNode measure:constrainedTextSize];
CGFloat finalWidth = self.textInsets.left + textSize.width + self.textInsets.right;
CGFloat finalHeight = self.textInsets.top + textSize.height + self.textInsets.bottom;
CGSize finalSize = CGSizeMake(finalWidth, finalHeight);
return finalSize;
}
- (void)layout
{
CGFloat textX = self.textInsets.left;
CGFloat textY = self.textInsets.top;
CGSize textSize = self.textNode.calculatedSize;
textNode.frame = CGRectMake(textX, textY, textSize.width, textSize.height);
}
- (NSAttributedString *) attributedString
{
return self.textNode.attributedString;
}
- (void)setAttributedString:(NSAttributedString *)attributedString
{
self.textNode.attributedString = attributedString;
[self invalidateCalculatedSize];
}
- (void)setTextInsets:(UIEdgeInsets)textInsets
{
_textInsets = textInsets;
[self invalidateCalculatedSize];
}
#end
2018: Now it is super easy to achieve the same effect, So just in case someone needs to add padding here is a Swift 4 solution: -
let messageLabel: ASTextNode = {
let messageNode = ASTextNode()
messageNode.textContainerInset = UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10)
return messageNode
}()

change position of Slide To Cancel

I'm using SlideToCancel as per requirements to my project but i'm unable to find how to change the position of button.
I have gone through all the code but cannot figure.
Here is the main code:
import
#import "SlideToCancelViewController.h"
#interface SlideToCancelViewController()
- (void) setGradientLocations:(CGFloat)leftEdge;
- (void) startTimer;
- (void) stopTimer;
#end
static const CGFloat gradientWidth = 0.2;
static const CGFloat gradientDimAlpha = 0.5;
static const int animationFramesPerSec = 8;
#implementation SlideToCancelViewController
#synthesize delegate;
// Implement the "enabled" property
- (BOOL) enabled {
return slider.enabled;
}
- (void) setEnabled:(BOOL)enabled{
slider.enabled = enabled;
label.enabled = enabled;
if (enabled) {
slider.value = 0.0;
label.alpha = 1.0;
touchIsDown = NO;
[self startTimer];
} else {
[self stopTimer];
}
}
- (UILabel *)label {
// Access the view, which will force loadView to be called
// if it hasn't already been, which will create the label
(void)[self view];
return label;
}
// Implement loadView to create a view hierarchy programmatically, without using a nib.
- (void)loadView {
// Load the track background
UIImage *trackImage = [UIImage imageNamed:#"sliderTrack.png"];
sliderBackground = [[UIImageView alloc] initWithImage:trackImage];
// Create the superview same size as track backround, and add the background image to it
UIView *view = [[UIView alloc] initWithFrame:sliderBackground.frame];
[view addSubview:sliderBackground];
// Add the slider with correct geometry centered over the track
slider = [[UISlider alloc] initWithFrame:sliderBackground.frame];
CGRect sliderFrame = slider.frame;
sliderFrame.size.width -= 46; //each "edge" of the track is 23 pixels wide
slider.frame = sliderFrame;
slider.center = sliderBackground.center;
slider.backgroundColor = [UIColor clearColor];
[slider setMinimumTrackImage:[UIImage imageNamed:#"sliderMaxMin-02.png"] forState:UIControlStateNormal];
[slider setMaximumTrackImage:[UIImage imageNamed:#"sliderMaxMin-02.png"] forState:UIControlStateNormal];
UIImage *thumbImage = [UIImage imageNamed:#"sliderThumb.png"];
[slider setThumbImage:thumbImage forState:UIControlStateNormal];
slider.minimumValue = 0.0;
slider.maximumValue = 1.0;
slider.continuous = YES;
slider.value = 0.0;
// Set the slider action methods
[slider addTarget:self
action:#selector(sliderUp:)
forControlEvents:UIControlEventTouchUpInside];
[slider addTarget:self
action:#selector(sliderDown:)
forControlEvents:UIControlEventTouchDown];
[slider addTarget:self
action:#selector(sliderChanged:)
forControlEvents:UIControlEventValueChanged];
// Create the label with the actual size required by the text
// If you change the text, font, or font size by using the "label" property,
// you may need to recalculate the label's frame.
NSString *labelText = NSLocalizedString(#"slide to cancel", #"SlideToCancel label");
UIFont *labelFont = [UIFont systemFontOfSize:24];
CGSize labelSize = [labelText sizeWithFont:labelFont];
label = [[UILabel alloc] initWithFrame:CGRectMake(0.0, 0.0, labelSize.width, labelSize.height)];
// Center the label over the slidable portion of the track
CGFloat labelHorizontalCenter = slider.center.x + (thumbImage.size.width / 2);
label.center = CGPointMake(labelHorizontalCenter, slider.center.y);
// Set other label attributes and add it to the view
label.textColor = [UIColor whiteColor];
label.textAlignment = UITextAlignmentCenter;
label.backgroundColor = [UIColor clearColor];
label.font = labelFont;
label.text = labelText;
[view addSubview:label];
[view addSubview:slider];
// This property is set to NO (disabled) on creation.
// The caller must set it to YES to animate the slider.
// It should be set to NO (disabled) when the view is not visible, in order
// to turn off the timer and conserve CPU resources.
self.enabled = NO;
// Render the label text animation using our custom drawing code in
// the label's layer.
label.layer.delegate = self;
// Set the view controller's view property to all of the above
self.view = view;
// The view is retained by the superclass, so release our copy
[view release];
}
- (void)didReceiveMemoryWarning {
// Releases the view if it doesn't have a superview.
[super didReceiveMemoryWarning];
// Release any cached data, images, etc that aren't in use.
}
- (void)viewDidUnload {
// Release any retained subviews of the main view.
[self stopTimer];
[sliderBackground release], sliderBackground = nil;
[slider release], slider = nil;
[label release], label = nil;
}
// UISlider actions
- (void) sliderUp: (UISlider *) sender
{
//filter out duplicate sliderUp events
if (touchIsDown) {
touchIsDown = NO;
if (slider.value != 1.0) //if the value is not the max, slide this bad boy back to zero
{
[slider setValue: 0 animated: YES];
label.alpha = 1.0;
[self startTimer];
}
else {
//tell the delagate we are slid all the way to the right
[delegate cancelled];
}
}
}
- (void) sliderDown: (UISlider *) sender
{
touchIsDown = YES;
}
- (void) sliderChanged: (UISlider *) sender
{
// Fade the text as the slider moves to the right. This code makes the
// text totally dissapear when the slider is 35% of the way to the right.
label.alpha = MAX(0.0, 1.0 - (slider.value * 3.5));
// Stop the animation if the slider moved off the zero point
if (slider.value != 0) {
[self stopTimer];
[label.layer setNeedsDisplay];
}
}
// animationTimer methods
- (void)animationTimerFired:(NSTimer*)theTimer {
// Let the timer run for 2 * FPS rate before resetting.
// This gives one second of sliding the highlight off to the right, plus one
// additional second of uniform dimness
if (++animationTimerCount == (2 * animationFramesPerSec)) {
animationTimerCount = 0;
}
// Update the gradient for the next frame
[self setGradientLocations:((CGFloat)animationTimerCount/(CGFloat)animationFramesPerSec)];
}
- (void) startTimer {
if (!animationTimer) {
animationTimerCount = 0;
[self setGradientLocations:0];
animationTimer = [[NSTimer
scheduledTimerWithTimeInterval:1.0/animationFramesPerSec
target:self
selector:#selector(animationTimerFired:)
userInfo:nil
repeats:YES] retain];
}
}
- (void) stopTimer {
if (animationTimer) {
[animationTimer invalidate];
[animationTimer release], animationTimer = nil;
}
}
// label's layer delegate method
- (void)drawLayer:(CALayer *)theLayer
inContext:(CGContextRef)theContext
{
// Set the font
const char *labelFontName = [label.font.fontName UTF8String];
// Note: due to use of kCGEncodingMacRoman, this code only works with Roman alphabets!
// In order to support non-Roman alphabets, you need to add code generate glyphs,
// and use CGContextShowGlyphsAtPoint
CGContextSelectFont(theContext, labelFontName, label.font.pointSize, kCGEncodingMacRoman);
// Set Text Matrix
CGAffineTransform xform = CGAffineTransformMake(1.0, 0.0,
0.0, -1.0,
0.0, 0.0);
CGContextSetTextMatrix(theContext, xform);
// Set Drawing Mode to clipping path, to clip the gradient created below
CGContextSetTextDrawingMode (theContext, kCGTextClip);
// Draw the label's text
const char *text = [label.text cStringUsingEncoding:NSMacOSRomanStringEncoding];
CGContextShowTextAtPoint(
theContext,
0,
(size_t)label.font.ascender,
text,
strlen(text));
// Calculate text width
CGPoint textEnd = CGContextGetTextPosition(theContext);
// Get the foreground text color from the UILabel.
// Note: UIColor color space may be either monochrome or RGB.
// If monochrome, there are 2 components, including alpha.
// If RGB, there are 4 components, including alpha.
CGColorRef textColor = label.textColor.CGColor;
const CGFloat *components = CGColorGetComponents(textColor);
size_t numberOfComponents = CGColorGetNumberOfComponents(textColor);
BOOL isRGB = (numberOfComponents == 4);
CGFloat red = components[0];
CGFloat green = isRGB ? components[1] : components[0];
CGFloat blue = isRGB ? components[2] : components[0];
CGFloat alpha = isRGB ? components[3] : components[1];
// The gradient has 4 sections, whose relative positions are defined by
// the "gradientLocations" array:
// 1) from 0.0 to gradientLocations[0] (dim)
// 2) from gradientLocations[0] to gradientLocations[1] (increasing brightness)
// 3) from gradientLocations[1] to gradientLocations[2] (decreasing brightness)
// 4) from gradientLocations[3] to 1.0 (dim)
size_t num_locations = 3;
// The gradientComponents array is a 4 x 3 matrix. Each row of the matrix
// defines the R, G, B, and alpha values to be used by the corresponding
// element of the gradientLocations array
CGFloat gradientComponents[12];
for (int row = 0; row < num_locations; row++) {
int index = 4 * row;
gradientComponents[index++] = red;
gradientComponents[index++] = green;
gradientComponents[index++] = blue;
gradientComponents[index] = alpha * gradientDimAlpha;
}
// If animating, set the center of the gradient to be bright (maximum alpha)
// Otherwise it stays dim (as set above) leaving the text at uniform
// dim brightness
if (animationTimer) {
gradientComponents[7] = alpha;
}
// Load RGB Colorspace
CGColorSpaceRef colorspace = CGColorSpaceCreateDeviceRGB();
// Create Gradient
CGGradientRef gradient = CGGradientCreateWithColorComponents (colorspace, gradientComponents,
gradientLocations, num_locations);
// Draw the gradient (using label text as the clipping path)
CGContextDrawLinearGradient (theContext, gradient, label.bounds.origin, textEnd, 0);
// Cleanup
CGGradientRelease(gradient);
CGColorSpaceRelease(colorspace);
}
- (void) setGradientLocations:(CGFloat) leftEdge {
// Subtract the gradient width to start the animation with the brightest
// part (center) of the gradient at left edge of the label text
leftEdge -= gradientWidth;
//position the bright segment of the gradient, keeping all segments within the range 0..1
gradientLocations[0] = leftEdge < 0.0 ? 0.0 : (leftEdge > 1.0 ? 1.0 : leftEdge);
gradientLocations[1] = MIN(leftEdge + gradientWidth, 1.0);
gradientLocations[2] = MIN(gradientLocations[1] + gradientWidth, 1.0);
// Re-render the label text
[label.layer setNeedsDisplay];
}
- (void)dealloc {
[self stopTimer];
[self viewDidUnload];
[super dealloc];
}
#end
Sorry for posting heavy code stuff.
P.S.: I know AppStore doesn't accepts this code but i'm interested to learn & do more on QuartzCore graphics than using interface builders.
Check this answer https://stackoverflow.com/a/25894355/1344237
You have to remove the label.layer.delegate = self;

Autoadjust content of UILabel

I have already determined the bounds of UILabel. Single line, 2-3 words. I have to change the font size. What is the best solution to adjust the content into strongly determined rectangle programmatically?
Set the minimum font scale of the label
_myLabel.adjustsFontSizeToFitWidth = YES;
_myLabel.minimumScaleFactor = 0.5f;
Use Autoshrink property in your XIB (or programmatically) and set minimum Font Size and your text will be adapted to the space. But with a minimum font.
I found the solution to check the sizes manually. The other solutions are working improperly. May be this code will help to somebody. Here the code to solve:
-(void) autoResizeLabel: (UILabel*) label withMaxWidth:(CGFloat)mw withMaxHeight:(CGFloat)mh
{
CGFloat fontSize = 1.f;
CGFloat outSize = fontSize;
CGFloat mDelta = 30.f;
CGFloat delta = 1.f;
BOOL activated = NO;
BOOL broken = NO;
for (float fSize = fontSize; fSize < fontSize + mDelta; fSize += delta)
{
CGRect r = [label.text boundingRectWithSize:label.frame.size options:NSStringDrawingUsesLineFragmentOrigin attributes:#{NSFontAttributeName:[UIFont systemFontOfSize:fSize]} context:nil];
CGFloat width = r.size.width;
CGFloat height = r.size.height;
if (mw <= width || mh <= height)
{
if (activated)
{
outSize = fSize - delta;
}
broken = YES;
break;
}
activated = YES;
//NSLog(#"%f;%f;%f",fSize,mw,mh);
}
if (activated && !broken) outSize = fontSize + mDelta - delta;
[label setFont:[UIFont systemFontOfSize:outSize]];
}

Horizantal slider with tick marks on iOS

Can i realise a horizontal slider with tick marks on iOS? There is not such option like in MacOS.
I actually wrote a tutorial on how to do this on my company's website:
http://fragmentlabs.com/blog/making-talking2trees-part-3-77
The quick answer for this is a custom method I wrote, and which is explained in the article above:
-(UIView*)tickMarksViewForSlider:(UISlider*)slider View:(UIView *)view
{
// set up vars
int ticksDivider = (slider.maximumValue > 10) ? 10 : 1;
int ticks = (int) slider.maximumValue / ticksDivider;
int sliderWidth = 364;
float offsetOffset = (ticks < 10) ? 1.7 : 1.1;
offsetOffset = (ticks > 10) ? 0 : offsetOffset;
float offset = sliderWidth / ticks - offsetOffset;
float xPos = 0;
// initialize view to return
view.frame = CGRectMake(view.frame.origin.x, view.frame.origin.y+1,
slider.frame.size.width, slider.frame.size.height);
view.backgroundColor = [UIColor clearColor];
// make a UIImageView with tick for each tick in the slider
for (int i=0; i < ticks; i++)
{
if (i == 0) {
xPos += offset+5.25;
}
else
{
UIView *tick = [[UIView alloc] initWithFrame:CGRectMake(xPos, 3, 2, 16)];
tick.backgroundColor = [UIColor colorWithWhite:0.7 alpha:1];
tick.layer.shadowColor = [[UIColor whiteColor] CGColor];
tick.layer.shadowOffset = CGSizeMake(0.0f, 1.0f);
tick.layer.shadowOpacity = 1.0f;
tick.layer.shadowRadius = 0.0f;
[view insertSubview:tick belowSubview:slider];
xPos += offset - 0.4;
}
}
// return the view
return view;
}
You'd basically apply this method to a view that sits behind your UISlider, and it creates the tick marks at the appropriate intervals. You can change how many ticks are visible by modifying the ticksDivider variable. The above example creates one per slider value unless the slider's maximumValue property is greater than 10 (my sliders had values of 5, 40 and 120), in which case I divided the value by 10.
You have to play with the offsetOffset value and the float value after xPos += offset+... to account for the width of your thumb image and slider cap insets (so the thumb button appears to be centered over each).
From #CarlGoldsmith - You'd have to program that yourself; UISliders on iOS don't have that functionality.
While ctlockey's solution certainly works, I wanted something simpler but also that allowed the thumb to snap to whichever tick mark it is closest to when the user releases it.
My solution is below. It is a subclass of UISlider that only overrides two methods. It is bare bones but would be a foundation for a more complex version.
-(void)endTrackingWithTouch:(UITouch *)touch
withEvent:(UIEvent *)event
{
[super endTrackingWithTouch:touch withEvent:event];
if (self.value != floorf(self.value))
{
CGFloat roundedFloat = (float)roundf(self.value);
[self setValue:roundedFloat animated:YES];
}
}
-(void)drawRect:(CGRect)rect
{
CGFloat thumbOffset = self.currentThumbImage.size.width / 2.0f;
NSInteger numberOfTicksToDraw = roundf(self.maximumValue - self.minimumValue) + 1;
CGFloat distMinTickToMax = self.frame.size.width - (2 * thumbOffset);
CGFloat distBetweenTicks = distMinTickToMax / ((float)numberOfTicksToDraw - 1);
CGFloat xTickMarkPosition = thumbOffset; //will change as tick marks are drawn across slider
CGFloat yTickMarkStartingPosition = self.frame.size.height / 2; //will not change
CGFloat yTickMarkEndingPosition = self.frame.size.height; //will not change
UIBezierPath *tickPath = [UIBezierPath bezierPath];
for (int i = 0; i < numberOfTicksToDraw; i++)
{
[tickPath moveToPoint:CGPointMake(xTickMarkPosition, yTickMarkStartingPosition)];
[tickPath addLineToPoint:CGPointMake(xTickMarkPosition, yTickMarkEndingPosition)];
xTickMarkPosition += distBetweenTicks;
}
[tickPath stroke];
}

Resources