I have a view, that have a drawRect method, I know that this method is the only way I control the View to draw something on it. So, I try to my drawing logic in this way:
- (void)drawRect:(CGRect)rect {
//my drawing code...
}
In my view, I use the IB to link this class.
[myView setNeedsDisplay];
It works, so, I designed to have a Command object inside the drawRect method, so that I can drawing dynamically based on my Cmd. Here is the code in the View after I modified:
- (void)drawRect:(CGRect)rect {
self.cmdToBeExecuted = [[DrawingSomethingCmd alloc] init];
[self.cmdToBeExecuted execute];
}
My DrawingsomthingCmd:
#implementation DrawingSomethingCmd
-(void)execute{
//my drawing code;
}
It works too. But the question is, how can I assign the self.cmdToBeExecuted dynamically.
Also, I changed my drawRect like this:
- (void)drawRect:(CGRect)rect {
[self.cmdToBeExecuted execute];
}
Because I have this to link with the IB,
IBOutlet myDrawingView *myView;
but after I type [myView ... ...], it don't allow me to get the variable cmdToBeExecuted. I ready make my variable accessible in .h:
#property (nonatomic, retain) Command *cmdToBeExecuted;
and .m also:
#synthesize cmdToBeExecuted;
Don't initialize the command inside the drawing rect. Initialize a default (maybe in viewDidLoad? it depends on what you are doing) somewhere as the view is created and then update them dynamically however you are doing this, whenever the need arises. So:
- (void)drawRect:(CGRect)rect
{
[[self commandToBeExecuted] execute];
}
and elsewhere:
// dynamically update the drawing
[myView setCommandToBeExected:[[[DrawingSomethingCommand alloc] init] autorelease]];
Related
I have an iPad app, using Storyboards, XCode 4.6 and iOS 6.1. I have a scene that contains a UIViewController. Inside that UIViewController, I have a UIScrollController, all created using IB. Programmatically, in viewDidLoad I created two (2) UIViews (one called subViewGrid, the other called subViewData) and added them to the UIViewController; they both display correctly in the Simulator. Here's the code:
- (void)viewDidLoad {
[super viewDidLoad];
// notify me when calendar has been tapped and CFGregorianDate has been updated
[[NSNotificationCenter defaultCenter] removeObserver:self];
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(calendarTapNotification:)
name:#"calendarDateSelected" object:nil ];
// UIScrollVIew settings
CGSize scrollableSize = CGSizeMake(760, 1379); // set size of scheduleView
[self.schedScrollView setContentSize:scrollableSize];
self.schedScrollView.contentInset = UIEdgeInsetsMake(0,0,44,44); // allow for scroll bar
self.schedScrollView.directionalLockEnabled = YES; // prevents diagonal scrolling
// create a sub-view to hold the appointment GRID
CGRect frame = CGRectMake(0,0,760,1390); // 110,48,760,1390
subViewGrid = [[UIView alloc] initWithFrame:frame];
subViewGrid.tag = 12; // use tag to get correct sub-view
subViewGrid.backgroundColor = [UIColor grayColor];
subViewGrid.alpha = 1.0; // make it opaque
[self.schedScrollView addSubview:subViewGrid];
// create a sub-view to hold the appointment DATA
frame = CGRectMake(110,48,670,750);
subViewData = [[UIView alloc] initWithFrame:frame];
subViewData.tag = 22; // use tag to get correct sub-view
subViewData.backgroundColor = [UIColor redColor];
subViewData.alpha = 0.2; // make it sort of transparent
[self.schedScrollView addSubview:subViewData];
[self.subViewGrid setNeedsDisplay]; // **** UPDATED ****
}
Here is the .h file contents for the UIViewController:
#interface CalendarViewController : UIViewController {
UIView *subViewGrid;
UIView *subViewData;
}
#property (strong, nonatomic) IBOutlet UIScrollView *schedScrollView;
- (void) calendarTapNotification:(NSNotification *) notification;
-(NSDate *)beginningOfDay:(NSDate *)date;
-(NSDate *)endOfDay:(NSDate *)date;
#end
In my drawRect method, I have some code that is supposed to draw a "grid" on the subViewGrid. The problem is drawRect never gets called.`
I have read the UIView Programmer's Guide and looked in SO and did a Google search, but found nothing that addresses the issue, which is: why won't [self.subViewGrid setNeedsDisplay] call drawRect from where I have it placed?
Your view controller needs to call setNeedsDisplay for the view it controls, not for itself. So, you want
[self.subViewGrid setNeedsDisplay]
This is just an error in your reading the documentation. Understanding the documentation is critical for objective-C programming so I'll try to help you get a grasp of it.
If you look at the documentation for setNeedsDisplay you will see that it is either a CALayer or UIView class method. If you then look at inheritance, you will see that UIView is UIResponder:NSObject and CALayer is NSObject. None of these inherit from UIViewController which is why you are getting the error. You need to call [self.subViewGrid setNeedsDisplay]
I am currently trying to refresh or clear my UIView draw but a lot of methods aren't working. I tried:
self.Draw.clearsContextBeforeDrawing
[self.Draw setNeedsDisplay];
self.Draw.removeFromSuperview;
My code:
-(void)drawPoint:(UITouch *)touch
{
PointLocation *currentLoc = [[PointLocation alloc] init];
currentLoc.location = [touch locationInView:self];
self.previousPoint = self.point;
self.point = currentLoc;
[self drawToBuffer];
[self setNeedsDisplay];
}
Is there any way to clear my uidraw? Or at least reload it?
There's a few basic problems here.
How is Draw declared? Follow cocoa naming conventions. Only Class names should be capitalized. Instances of a class should start with a lowercase letter.
I think what you want is:
#interface Draw: UIView
#end
#implementation Draw
- (void) drawRect: (CGRect) r {
// here you will draw whatever you want in your view.
}
#end
Draw* draw;
in your drawPoint method:
[draw setNeedsDisplay];
For more details see The View Drawing Cycle:
http://developer.apple.com/library/ios/documentation/UIKit/Reference/UIView_Class/UIView/UIView.html#//apple_ref/doc/uid/TP40006816-CH3-SW136
For bonus points, name your view something more descriptive than Draw. It is a view of something, a window containing some content. It is not a verb.
I'm trying to do draw a fancy UIButton using Quartz. I've declared my own button class like this:
#interface MyButton : UIButton
#end
In the .m file I'm constructing the button:
- (id)initWithCoder:(NSCoder *)aDecoder
{
self = [super initWithCoder:aDecoder];
if (self) {
// Initialization code
CALayer *buttonLayer = self.layer;
buttonLayer.masksToBounds = YES;
CALayer *customDrawn = [CALayer layer];
customDrawn.delegate = self;
customDrawn.masksToBounds = YES;
[buttonLayer insertSublayer:customDrawn atIndex:0];
[customDrawn setNeedsDisplay];
}
return self;
}
But this results in some kind of recursion and finally fails with a EXC_BAD_ACCESS.
I've implemented a method drawLayer: inContext:, but it still crashes. The only way I can avoid the crash is by removing the delegate-assignment, but then I can't do any of the custom drawing I want to implement.
How can I make this work?
As described in the question mentioned by Kurt Revis, a UIView (such as UIButton) can't be used as a delegate for a sublayer. (It is already the delegate for the "main" layer of the UIView and can't be used as a delegate for another layer.) The solution is to use another object as a delegate which can be a "private" class just used to implement the drawLayer: inContext: method.
Well, here's the situation:
I've got...
a custom class with an UIImageView-property, let's call it the Enemy-class
a ViewController
a NSMutableArray to help create multiple instances of Enemy (called enemies)
and what I want:
be able to create an unlimited amount of Enemy-Instances through a method in my ViewController (like [self spawnEnemy];, where self is the ViewController)
and, subsequently, display the UIImageView property (let's call it "enemyImage") on the view that is controlled by my ViewController
I've tried something like this:
-(Enemy *) spawnEnemy
{
Enemy *tempEnemy = [Enemy new];
[enemies addObject:(Enemy*)tempEnemy];
[self.view addSubview:(UIImageView*)[[enemies objectAtIndex:[enemies count]] enemyImage]];
//randomLocation is declared in the Enemy-Class and just assigns a random
//CGPoint to self.enemyImage.center
[[enemies objectAtIndex:[enemies count]] randomLocation];
return [[enemies objectAtIndex:[enemies count]]createEnemy];
}
This runs without errors, randomLocation gets called (tried with NSLog), AND if I do something like this in another Method of ViewController:
[[self spawnEnemy] enemyTestMethod];
enemyTestMethod is being executed as well.
But still, no enemieViews are displayed on the screen...
What am I doing wrong?
Thank you so much for your help and time.
==== Edit ====
Here's the relevant code from Enemy.h/Enemy.m:
#interface Enemy : NSObject
{
UIImageView *enemyImage;
}
#property (nonatomic, retain) IBOutlet UIImageView *enemyImage;
-(Enemy*) createEnemy;
//Enemy.m
#implementation Enemy
#synthesize enemyImage, speed;
-(Enemy *) createEnemy
{
self.enemyImage = [[UIImageView alloc] init];
[self.enemyImage setImage:[UIImage imageNamed:#"enemy.png"]];
return self;
}
I also corrected the last line in the spawnEnemy-Method to properly send createEnemy.
You don't include the code in Enemy where you alloc/init the UIImageView property. Unless this code explicitly specifies a CGRect with the size and origin that you want, the view will be initialized with CGRectZero, which means even if you're correctly adding the subview (and it looks like you are) you still won't see it anywhere.
Post the Enemy code, and the problem will probably be immediately apparent.
Have you called -createEnemy before you added them to your view?
OK, you've got this checked.
Then maybe you should check as #MusiGenesis suggested.
To do this, you need to inspect the properties of your enemyImage.
You can do this in either of the following ways:
print its frame.size by:
NSLog(#"enemyImage frame size: %#", NSStringFromCGRect(enemy.enemyImage));
set a breakpoint where you feel great, and check with your debugger:
p (CGRect)[[enemy enemyImage] frame]
I'm working on a custom implementation of UISegmentedControl.
I'd like to create a component that able to receive config data and from which obtain a custom View similar to UISegmentedControl.
I started subclassing a UIView and i can create a custom UISegmentedControl with this code:
CustomSegment *segment = [[CustomSegment alloc]
initWithTitles:[NSArray arrayWithObjects:#"one",#"two",nil]];
[self.window addSubview:segment];
But now i'd like to improve my class and add some more customizable parameters to it.
For example i'd like add a custom separators, define the button fonts and so on... here my doubt:
Is it better to work on a UIView subClass or you suggest me to subclass a UIViewController, where i can manage View hierarchy in method like -(void)loadView and -(void)viewDidLoad ?
In a simple UIView subclass, when i launch the custom init method, i setup immediately subviews... while using a UIViewController i can call custom init and define how my subview is builded into -(void)loadView.
Don't use an UIViewController, just extend the UIView class like you did and keep extending its functionality.
Remember to save a pointer to each subview you add (i.e. buttons) in order to be able to access them later.
Define custom setters, for example, a custom setter for changing a button label title would be:
- (void) setButton1Title:(NSString*)str forState:(UIControlState)state{
//You can add some control here
if ([str length] > 20) return;
[_button1 setTitle:str forState:state]; //_button1 is my reference to the button
}
And so on. Don't provide direct access to your subviews, use methods instead.
Also, you can use "layoutSubviews" method to define how your views are going to be displayed in your custom view.
Hope it helps you.
Edit: In your case, I don't see why using lauoutSubviews method but I want to show you what I was trying to say.
Lets say that for example I need to create an UIView class to represent a "Contact" object in my application.
This is what I would do:
#interface ContactView : UIView{
UILabel* _nameLabel;
UILabel* _ageLabel;
Contact* _contact;
}
#property (retain) Contact* contact;
#end
#implementation ContactView
#synthetize contact = _contact;
-(id)initWithContact:(Contact*)c{
self = [super init];
if (self) {
_nameLabel = [[UILabel alloc] init];
_nameLabel.frame = CGRectZero;
[self addSubview:_nameLabel];
[_nameLabel release];
_ageLabel = [[UILabel alloc] init];
_ageLabel.frame = CGRectZero;
[self addSubview:_ageLabel];
[_ageLabel release];
self.contact = c;
}
}
- (void) layoutSubviews{
[super layoutSubviews];
_nameLabel.frame = CGRectMake(0.0f, 0.0f, 200.0f, 25.0f);
_ageLabel.frame = CGRectMake(0.0f, 25.0f, 200.0f, 25.0f);
if (self.contact){
_nameLabel.text = self.contact.name;
_ageLabel.text = self.contact.age;
}else{
_nameLabel.text = #"Unavailable";
_ageLabel.text = #"Unavailable";
}
}
- (void) setContact:(Contact*)c{
self.contact = c;
[self layoutSubviews];
}
#end
Check out how the "layoutSubiews" is used to set the correct frame and data to the labels.
Usually, I use it a lot when creating custom UITableViewCells where you have to reuse the view.
Let me know if I'm being confusing.