I am new at objective c and I need some help to create a label which appears in all my ViewControllers with the same text but this text will be changed constantly.
Thank you guys.
You can create Category class for this
in .h File
//
// UILabel+withString.h
//
#import <Foundation/Foundation.h>
#interface UILabel (withString)
+ (UILabel *)labelWithString:(NSString *)string
font:(UIFont *)font
color:(UIColor *)color
container:(CGRect)container
origin:(CGPoint)origin;
#end
In .m File
//
// UILabel+withString.m
//
#import "UILabel+withString.h"
#implementation UILabel (withString)
+ (UILabel *)labelWithString:(NSString *)string
font:(UIFont *)font
color:(UIColor *)color
container:(CGRect)container
origin:(CGPoint)origin {
CGSize size = [string sizeWithFont:font constrainedToSize:container.size
lineBreakMode:UILineBreakModeTailTruncation];
UILabel *label = [[[UILabel alloc]
initWithFrame:CGRectMake(origin.x, origin.y, container.size.width, size.height)] autorelease];
label.text = string;
label.font = font;
label.textColor = color;
label.textAlignment = UITextAlignmentLeft;
label.numberOfLines = 1;
label.lineBreakMode = UILineBreakModeTailTruncation;
label.backgroundColor = [UIColor clearColor];
return label;
}
#end
then in view controller you can call this
Related
I would like to add a progress bar under the navigation bar which will indicate the progress of the scroll of a UIScrollView, I use (not work) : I do
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
self.progressView.progress = scrollView.contentOffset.y;
}
check now I created one demo:
#import "ViewController.h"
#interface ViewController ()<UIScrollViewDelegate>{
UIScrollView *scroll;
UIProgressView *indicater;
}
#end
#implementation ViewController
- (void)viewDidLoad {
indicater=[[UIProgressView alloc]initWithFrame:CGRectMake(0, 65, 320,10)];
indicater.backgroundColor=[UIColor redColor];
indicater.progress = 0.0;
indicater.hidden=false;
[self.view addSubview:indicater];
scroll=[[UIScrollView alloc]initWithFrame:CGRectMake(10, 80,300, 200)];
scroll.backgroundColor=[UIColor greenColor];
scroll.userInteractionEnabled=YES;
scroll.delegate=self;
scroll.contentSize = CGSizeMake(300 ,5000);
[self.view addSubview:scroll];
}
- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
CGPoint offset = scroll.contentOffset;
CGRect bounds = scroll.bounds;
CGSize size = scroll.contentSize;
UIEdgeInsets inset = scroll.contentInset;
float y = offset.y + bounds.size.height - inset.bottom;
float h = size.height;
NSLog(#"%f",y);
NSLog(#"%f",h);
NSNumber *num=[NSNumber numberWithFloat:y];
NSNumber *num1=[NSNumber numberWithFloat:h];
[self UpdateProgressbar:num TotalscrollLenrth:num1];
}
-(void)UpdateProgressbar:(NSNumber*)currentscrollLenrth TotalscrollLenrth:(NSNumber*)n
{
NSString *totalLength = [NSString stringWithFormat:#"%#", n];
NSLog(#"%#", totalLength);
NSString *currentScrool = [NSString stringWithFormat:#"%#", currentscrollLenrth];
NSLog(#"%#", currentScrool);
if (currentscrollLenrth <= n) {
[indicater setProgress:([currentScrool intValue]/[totalLength floatValue])];
}
else {
// do somithig
}
}
I try to add OpenSans-Regular.ttf to my Xcode project:
1)I add the file into the project.
2) add font in plist.
3)check if the file add to Bundle resources
- (void)viewDidLoad
{
[super viewDidLoad];
UILabel *myLable = [[UILabel alloc]initWithFrame:CGRectMake(100, 100, 100, 50)];
myLable.text = #"TEST RR";
[myLable setFont:[UIFont fontWithName:#"OpenSans-Regular" size:30]];
myLable.textColor = [UIColor whiteColor];
myLable.backgroundColor = [UIColor blackColor];
[self.view addSubview:myLable];
NSLog (#"Font families: %#", myLable.font.familyName);
}
and the font not work !
As suggested by #keyur bhalodiya you have to use the font name like #"OpenSnas" for regular fonts
Create a custom label subclass of UILabel 'CustomFontLabel'
in CustomFontLabel.h define property to set the font name
#interface CustomFontLabel : UILabel
#property (nonatomic) IBInspectable NSString *overrideFontName;
#end
In the .m file add the below code
- (void)setOverrideFontName:(NSString *)overrideFontName
{
if (![_overrideFontName isEqualToString:overrideFontName])
{
_overrideFontName = overrideFontName;
self.font = self.font;
}
}
- (void)setFont:(UIFont *)font
{
NSString *overrideFontName = self.overrideFontName;
if (overrideFontName != nil)
{
font = [UIFont fontWithName:overrideFontName size:font.pointSize];
}
[super setFont:font];
}
With the IBInspectable you can even set the overrideFontName property from Storyboard also. Don't forget to set the label class to CustomLabel in the storyboard. Try that and let me know, if it's working or not..!
I have a UITextView where the user can create notes and save into a plist file.
I want to be able to show lines just like a normal notebook. The problem I have is
that the text won't align properly.
The image below explains the problem quite well.
This is the background I use to create the lines like the Notes.app
This is my code for creating the background for my UITextView:
textView.font = [UIFont fontWithName:#"MarkerFelt-Thin" size:19.0];
textView.backgroundColor = [UIColor colorWithPatternImage: [UIImage imageNamed: #"Notes.png"]];
I know that the UIFont.lineHeight property is only available in > iOS 4.x.
So I wonder if there is another solution to my problem?
You should try and draw your lines programmatically rather than using an image. Here's some sample code of how you could accomplish that. You can subclass UITextView and override it's drawRect: method.
NoteView.h
#import <UIKit/UIKit.h>
#interface NoteView : UITextView <UITextViewDelegate> {
}
#end
NoteView.m
#import "NoteView.h"
#implementation NoteView
- (id)initWithFrame:(CGRect)frame {
self = [super initWithFrame:frame];
if (self) {
self.backgroundColor = [UIColor colorWithRed:1.0f green:1.0f blue:0.6f alpha:1.0f];
self.font = [UIFont fontWithName:#"MarkerFelt-Thin" size:19];
}
return self;
}
- (void)drawRect:(CGRect)rect {
//Get the current drawing context
CGContextRef context = UIGraphicsGetCurrentContext();
//Set the line color and width
CGContextSetStrokeColorWithColor(context, [UIColor colorWithRed:0.0f green:0.0f blue:0.0f alpha:0.2f].CGColor);
CGContextSetLineWidth(context, 1.0f);
//Start a new Path
CGContextBeginPath(context);
//Find the number of lines in our textView + add a bit more height to draw lines in the empty part of the view
NSUInteger numberOfLines = (self.contentSize.height + self.bounds.size.height) / self.font.leading;
//Set the line offset from the baseline. (I'm sure there's a concrete way to calculate this.)
CGFloat baselineOffset = 6.0f;
//iterate over numberOfLines and draw each line
for (int x = 0; x < numberOfLines; x++) {
//0.5f offset lines up line with pixel boundary
CGContextMoveToPoint(context, self.bounds.origin.x, self.font.leading*x + 0.5f + baselineOffset);
CGContextAddLineToPoint(context, self.bounds.size.width, self.font.leading*x + 0.5f + baselineOffset);
}
//Close our Path and Stroke (draw) it
CGContextClosePath(context);
CGContextStrokePath(context);
}
#end
MyViewController.h
#import <UIKit/UIKit.h>
#import "NoteView.h"
#interface MyViewController : UIViewController <UITextViewDelegate> {
NoteView *note;
}
#property (nonatomic, retain) NoteView *note;
#end
MyViewController.m
#import "MyViewController.h"
#import "NoteView.h"
#define KEYBOARD_HEIGHT 216
#implementation MyViewController
#synthesize note;
- (void)loadView {
[super loadView];
self.note = [[[NoteView alloc] initWithFrame:self.view.bounds] autorelease];
[self.view addSubview:note];
note.delegate = self;
note.text = #"This is the first line.\nThis is the second line.\nThis is the ... line.\nThis is the ... line.\nThis is the ... line.\nThis is the ... line.\nThis is the ... line.\n";
}
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
[note setNeedsDisplay];
}
- (void)textViewDidBeginEditing:(UITextView *)textView {
CGRect frame = self.view.bounds;
frame.size.height -= KEYBOARD_HEIGHT;
note.frame = frame;
}
- (void)textViewDidEndEditing:(UITextView *)textView {
note.frame = self.view.bounds;
}
- (void)dealloc {
[note release];
[super dealloc];
}
Take a look at Apple's documentation for Managing the Keyboard, specifically "Moving Content That Is Located Under the Keyboard". It explains how to listen for NSNotifcations and adjust your views properly.
I think the problem is with your image, the yellow space over the line is creating the problem.
You should edit the image.
And nice work.
I have a storyboard which loads loads a custom UIView. Also a sub view is added to the view in the storyboard. It worked fine until I overwrote the drawRect method of the sub view, then I just saw a black rectangle instead of the subview. Here is the code:
#import <UIKit/UIKit.h>
#import "MySubview.h"
#interface MyView : UIView
#end
#import "MyView.h"
#implementation MyView
- (void) awakeFromNib
{
CGRect frame = [self frame];
MySubview* sv = [[MySubview alloc] initWithFrame:frame];
[self addSubview:sv];
}
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
// Initialization code
}
return self;
}
#end
#import <UIKit/UIKit.h>
#interface MySubview : UIView
#property (retain, nonatomic) NSString* text;
#property (retain, nonatomic) UILabel* label;
#end
#import "MySubview.h"
#implementation MySubview
#synthesize text, label;
- (void)attachLabel
{
text = #"Hello";
label = [[UILabel alloc] init];
[label setText:text];
[label setFont:[UIFont fontWithName:#"Futura" size:18]];
[label setBackgroundColor:[UIColor clearColor]];
[label sizeToFit];
CGRect labelFrame = label.frame;
labelFrame.origin.x = (self.frame.size.width - labelFrame.size.width) / 2;
labelFrame.origin.y = (self.frame.size.height - labelFrame.size.height) / 2;
label.frame = labelFrame;
[self addSubview:label];
}
- (void)awakeFromNib
{
[self attachLabel];
}
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
[self attachLabel];
}
return self;
}
// Works if I comment this out!
- (void)drawRect:(CGRect)rect
{
}
#end
Update - Added drawing code below:
- (void)drawRectWithRoundBorders:(CGRect)rect
{
[super drawRect:rect];
// Parameters used for drawing.
const CGFloat lineWidth = 5;
const CGFloat shadowOffset = 3;
const CGFloat shadowBlur = 4;
const CGFloat spaceToBB = 10; // Space to the bounding box of this view.
const CGFloat cornerRadii = 5;
const CGFloat lineColor[4] = { 0, 0, 0, 1 };
CGContextRef ctx = UIGraphicsGetCurrentContext();
CGContextSetLineWidth(ctx, lineWidth);
CGContextSetStrokeColor(ctx, lineColor);
CGContextSetShadow(ctx, CGSizeMake(shadowOffset, shadowOffset), shadowBlur);
CGRect innerRect = rect;
innerRect.size.width -= 2*spaceToBB;
innerRect.size.height -= 2*spaceToBB;
innerRect.origin.x += spaceToBB;
innerRect.origin.y += spaceToBB;
UIBezierPath *path =
[UIBezierPath bezierPathWithRoundedRect:innerRect
byRoundingCorners:UIRectCornerAllCorners
cornerRadii:CGSizeMake(cornerRadii, cornerRadii)
];
CGContextAddPath(ctx, path.CGPath);
CGContextStrokePath(ctx);
}
- (void)drawRect:(CGRect)rect
{
[self drawRectWithRoundBorders:rect];
}
Update
It seems to work when I fill the bounding box of the sub view with some color first.
CGContextRef ctx = UIGraphicsGetCurrentContext();
CGFloat white[] = {1, 1, 1, 0.5};
CGContextSetFillColor(ctx, white);
CGContextAddRect(ctx, rect);
CGContextFillPath(ctx);
Just add [self setOpaque:NO] in your initWithFrame: method.
That's because your drawRect is doing nothing. You override drawRect if you want to do custom drawing. So:
If you don't want to do custom drawing then don't override drawRect.
If you do want to do custom drawing then actually do something in drawRect.
I have created the following subclass to do some custom drawing:
// DocumentIconView.h
#interface DocumentIconView : UIView
{
UIImageView *documentIconView;
CloseHandle *closeHandle;
UILabel *filenameLabel;
}
#property (nonatomic, strong) UIImageView *documentIconView;
#property (nonatomic, strong) CloseHandle *closeHandle;
#property (nonatomic, strong) UILabel *filenameLabel;
+ (DocumentIconView *)documentIconWithFrame:(CGRect)viewFrame
previewImage:(UIImage *)previewImage
title:(NSString *)title;
This works well for the most part (I can instantiate objects, and do custom drawing), however, I cannot access some of its properties from another classes.
DocumentIconView *iconView = [DocumentIconView documentIconWithFrame:frame
previewImage:[UIImage imageNamed:#"GenericDocumentIcon.png"]
title:[NSString stringWithFormat:#"test"]];
iconView.backgroundColor = [UIColor lightGrayColor]; // this works
iconView.filenameLabel.backgroundColor = [UIColor darkGrayColor]; // this does not work - no error message
[documentsView addSubview:iconView];
I can read and write first-level properties, but cannot drill deeper; when trying to read properties, the value returned is (null)
I am fairly new at subclassing, so I think I am missing something really obvious here. Any help would be greatly appreciated.
EDIT: the method for instantiating the view in question:
+ (DocumentIconView *)documentIconWithFrame:(CGRect)viewFrame
previewImage:(UIImage *)previewImage
title:(NSString *)title
{
DocumentIconView *view = [[DocumentIconView alloc] initWithFrame:viewFrame];
// Close handle's size is assigned here
CGSize closeHandleSize = CGSizeMake(27, 27);
// The document preview image's frame is calculated by shrinking it by the close handle's size
CGRect documentPreviewFrame = CGRectMake(closeHandleSize.width / 2,
closeHandleSize.height / 2,
viewFrame.size.width - closeHandleSize.width,
viewFrame.size.height - closeHandleSize.height - 20); // 20 points is the filenameLabel's height
UIImageView *documentPreviewView = [[UIImageView alloc] initWithFrame:documentPreviewFrame];
documentPreviewView.contentMode = UIViewContentModeScaleAspectFit;
documentPreviewView.backgroundColor = [UIColor clearColor];
documentPreviewView.image = previewImage;
[view addSubview:documentPreviewView];
CGRect closeHandleFrame = CGRectMake(0, 0, closeHandleSize.width, closeHandleSize.height);
CloseHandle *closeHandleView = [[CloseHandle alloc] initWithFrame:closeHandleFrame];
closeHandleView.alpha = 0.0;
closeHandleView.tag = kCloseHandleTag;
[view addSubview:closeHandleView];
CGRect filenameFrame = CGRectMake(0,
viewFrame.size.height - 20,
viewFrame.size.width,
20);
UILabel *filenameLabel = [[UILabel alloc] initWithFrame:filenameFrame];
filenameLabel.backgroundColor = [UIColor clearColor];
filenameLabel.text = title;
filenameLabel.font = [UIFont boldSystemFontOfSize:17];
filenameLabel.textColor = [UIColor whiteColor];
filenameLabel.textAlignment = UITextAlignmentCenter;
[view addSubview:filenameLabel];
view.tag = kDocumentIconTag;
return view;
}
In your documentIconWithFrame:... method you're using a local variable (filenameLabel) that you're adding to the view. That means your instance variable is never instantiated and is always nil.
Just change this:
UILabel *filenameLabel = [[UILabel alloc] initWithFrame:filenameFrame];
to this:
filenameLabel = [[UILabel alloc] initWithFrame:filenameFrame];
and the same for the other instance variables.