I am using GitHub project https://github.com/mayuur/MJParallaxCollectionView
I am trying to add a UIView and UILabel to the cells being displayed. I have tried so many solutions it would probably just be easier to ask someone how to do it.
So with that can someone add a UIView and UILabel to the UICollectionView displaying some text? This can be done programmatically or via storyboard, whichever suits your style.
I tried adding related logic in MJCollectionViewCell.m setupImageView method. Also, tried MJRootViewController cellForItemAtIndexPath method. But I still can't get the UIView and UILabel to display over the UIImage object in MJCollectionViewCell.
#property (nonatomic, strong, readwrite) UIImage *image;
MJCollectionViewCell.h
//
// MJCollectionViewCell.h
// RCCPeakableImageSample
//
// Created by Mayur on 4/1/14.
// Copyright (c) 2014 RCCBox. All rights reserved.
//
#import <UIKit/UIKit.h>
#define IMAGE_HEIGHT 200
#define IMAGE_OFFSET_SPEED 25
#interface MJCollectionViewCell : UICollectionViewCell
/*
image used in the cell which will be having the parallax effect
*/
#property (nonatomic, strong, readwrite) UIImage *image;
/*
Image will always animate according to the imageOffset provided. Higher the value means higher offset for the image
*/
#property (nonatomic, assign, readwrite) CGPoint imageOffset;
//#property (nonatomic,readwrite) UILabel *textLabel;
#property (weak, nonatomic) IBOutlet UILabel *textLabel;
#property (weak, nonatomic) IBOutlet UIImageView *cellImage;
#property (nonatomic,readwrite) NSString *text;
#property(nonatomic,readwrite) CGFloat x,y,width,height;
#property (nonatomic,readwrite) NSInteger lineSpacing;
#property (nonatomic, strong) IBOutlet UIView* overlayView;
#end
MJCollectionViewCell.m
// MJCollectionViewCell.m
// RCCPeakableImageSample
//
// Created by Mayur on 4/1/14.
// Copyright (c) 2014 RCCBox. All rights reserved.
//
#import "MJCollectionViewCell.h"
#interface MJCollectionViewCell()
#property (nonatomic, strong, readwrite) UIImageView *MJImageView;
#end
#implementation MJCollectionViewCell
- (instancetype)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) [self setupImageView];
return self;
}
- (id)initWithCoder:(NSCoder *)aDecoder {
self = [super initWithCoder:aDecoder];
if (self) [self setupImageView];
return self;
}
/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect
{
// Drawing code
}
*/
#pragma mark - Setup Method
- (void)setupImageView
{
// Clip subviews
self.clipsToBounds = YES;
/*
// Add image subview
self.MJImageView = [[UIImageView alloc] initWithFrame:CGRectMake(self.bounds.origin.x, self.bounds.origin.y, self.bounds.size.width, IMAGE_HEIGHT)];
self.MJImageView.backgroundColor = [UIColor redColor];
self.MJImageView.contentMode = UIViewContentModeScaleAspectFill;
self.MJImageView.clipsToBounds = NO;
[self addSubview:self.MJImageView];
*/
//New Code in method
// Add image subview
self.MJImageView = [[UIImageView alloc] initWithFrame:CGRectMake(self.bounds.origin.x, self.bounds.origin.y, self.bounds.size.width, IMAGE_HEIGHT)];
self.MJImageView.backgroundColor = [UIColor redColor];
self.MJImageView.contentMode = UIViewContentModeScaleAspectFill;
self.MJImageView.clipsToBounds = NO;
//self.overlayView.backgroundColor = [UIColor colorWithWhite:0.0f alpha:0.4f];
// UIView *anotherView = [[UIView alloc]initWithFrame:CGRectMake(0.0, 0.0, 20.0, 20.0)];
// UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(0.0, 0.0, 50.0, 20.0)];
// label.text = #"Hello";
// [anotherView addSubview:label];
[self addSubview:self.MJImageView];
[self addSubview:self.overlayView];
[self addSubview:self.textLabel];
}
# pragma mark - Setters
- (void)setImage:(UIImage *)image
{
// Store image
self.MJImageView.image = image;
// Update padding
[self setImageOffset:self.imageOffset];
}
- (void)setImageOffset:(CGPoint)imageOffset
{
// Store padding value
_imageOffset = imageOffset;
// Grow image view
CGRect frame = self.MJImageView.bounds;
CGRect offsetFrame = CGRectOffset(frame, _imageOffset.x, _imageOffset.y);
self.MJImageView.frame = offsetFrame;
}
//This was added from MPSkewed may need to remove if not called.
- (void)setText:(NSString *)text{
_text=text;
if (!self.textLabel) {
CGFloat realH=self.height*2/3-self.lineSpacing;
CGFloat latoA=realH/3;
// self.textLabel=[[UILabel alloc] initWithFrame:CGRectMake(10,latoA/2, self.width-20, realH)];
self.textLabel.layer.anchorPoint=CGPointMake(.5, .5);
self.textLabel.font=[UIFont fontWithName:#"HelveticaNeue-ultralight" size:38];
self.textLabel.numberOfLines=3;
self.textLabel.textColor=[UIColor whiteColor];
self.textLabel.shadowColor=[UIColor blackColor];
self.textLabel.shadowOffset=CGSizeMake(1, 1);
self.textLabel.transform=CGAffineTransformMakeRotation(-(asin(latoA/(sqrt(self.width*self.width+latoA*latoA)))));
[self addSubview:self.textLabel];
}
self.textLabel.text=text;
}
#end
In the .h of the cell:
#property (strong, nonatomic, readonly) UILabel *label
In the .m of the cell:
#property (strong, nonatomic, readwrite) UILabel *label
In the setupImageView method (which you should probably rename to be more generic), after the image view is created, something like this:
self.label = [[UILabel alloc] initWithFrame:someFrame]; // or CGRectZero if you are using auto layout
self.label.textColor = ...; // any other setup you want to do
[self addSubview:self.label];
self.label.frame = ...; // or set it up using auto layout
And in your data source’s -collectionView:cellForItemAtIndexPath:
cell.label.text = #"some text";
That is a simple approach. In practice, I would probably expose a property for the string only, not the whole label, but that depends on what you are doing and how much control you need.
Related
I have 4 screens that have one almost the same view:
And one screen have the same view but with slightly different UI:
So, my question: Can I use one xib and adapt states (active, inactive) and change ui for different screen? How I can do it?
Here is an example of this kind of class
In Your .m file of custom XIB class if you are using objective-c.
- (void)foo:(NSString*)labelText andButtonText:(NSString*)buttonTitle {
//Do your code here for some screen like change labels and button text
}
- (void)bar:(NSString*)labelText andButtonText:(NSString*)buttonTitle {
//Do your code here for some another screen and change labels and button text
}
In Your .h file of custom XIB class if you are using objective-c.
- (void)foo:(NSString*)labelText andButtonText:(NSString*)buttonTitle;
- (void)bar:(NSString*)labelText andButtonText:(NSString*)buttonTitle;
In your view controller where you want to display the custom UI
Create an instance of your xib or add through interfacebuilder
And On your instance of custom class call the method as required.
Below is a class I've used in one of my project to get a clear understanding.
#import <UIKit/UIKit.h>
#import "DYRateView.h"
#interface LevelAndRankDetails : UIView
#property (nonatomic, strong) IBOutlet UIView* contentView;
#property (nonatomic, strong) IBOutlet UIView* viewContainer;
#property (nonatomic, strong) IBOutlet UILabel* lblLevel;
#property (nonatomic, strong) IBOutlet UILabel* lblRanking;
#property (weak, nonatomic) IBOutlet DYRateView *viewRate;
- (void)setLevel:(NSNumber*)level andRanking:(NSNumber*)ranking;
- (void)setupUI;
#end
.m File
#import "LevelAndRankDetails.h"
#import "AppDelegate.h"
#import "Constants.h"
#implementation LevelAndRankDetails
/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
// Drawing code
}
*/
- (id)initWithFrame:(CGRect)frame {
if (self = [super initWithFrame:frame]){
[self commonSetup];
}
return self;
}
-(id)initWithCoder:(NSCoder *)aDecoder
{
self = [super initWithCoder:aDecoder];
if (self)
{
[self commonSetup];
}
return self;
}
- (void)layoutSubviews {
[super layoutSubviews];
}
- (void)viewFromNibForClass {
[[NSBundle mainBundle] loadNibNamed:[[self class] description] owner:self options:nil];
[self addSubview:self.contentView];
self.contentView.frame = self.bounds;
}
- (void)commonSetup {
[self viewFromNibForClass];
//For View's Corner Radius
self.contentView.layer.cornerRadius = 12;
self.contentView.layer.masksToBounds = YES;
self.contentView.backgroundColor = kDefaultBackgroundGreyColor;
self.viewContainer.backgroundColor = kDefaultBackgroundGreyColor;//[UIColor clearColor];
self.backgroundColor = kDefaultBackgroundGreyColor;
//self.viewContainer.backgroundColor = UIColorFromRGB(0xBB9657);//[kLearnFromLightColor colorWithAlphaComponent:0.5];
self.viewRate.rate = 0;
self.viewRate.editable = NO;
self.viewRate.delegate = nil;
self.viewRate.alignment = RateViewAlignmentCenter;
self.viewRate.backgroundColor = [UIColor clearColor];
[self.viewRate setEmptyStarImage:[UIImage imageNamed:#"StarEmpty"]];
UIImage* imageFullStar = [[UIImage imageNamed:#"StarFull"] imageTintedWithColor:kSliderDarkYellowColor];
[self.viewRate setFullStarImage:imageFullStar];
self.lblLevel.textColor = [UIColor whiteColor];
self.lblRanking.textColor = [UIColor whiteColor];
//For Teacher label
}
- (void)setupUI {
self.contentView.layer.cornerRadius = 0;
self.contentView.layer.masksToBounds = YES;
self.contentView.backgroundColor = [UIColor clearColor];
self.viewContainer.backgroundColor = [UIColor clearColor];//[UIColor clearColor];
self.backgroundColor = [UIColor clearColor];
}
- (void)setRanking:(CGFloat)ranking {
self.viewRate.rate = ranking;
}
- (void)setLevel:(NSNumber*)level {
self.lblLevel.text = [NSString stringWithFormat:#"Level : %#",level];
}
- (void)setLevel:(NSNumber*)level andRanking:(NSNumber*)ranking {
if (level.integerValue > 0) {
[self setLevel:level];
}
if (ranking.doubleValue > 0) {
CGFloat rankingConverted = ranking.floatValue;
[self setRanking:rankingConverted];
}
}
#end
And this is how you use it in your view controller
LevelAndRankDetails* toolTipCustomView = [[LevelAndRankDetails alloc] initWithFrame:CGRectMake(0, 0, 250, 66)];
toolTipCustomView.backgroundColor = [UIColor blackColor];
[toolTipCustomView setLevel:#(10) andRanking:#(3)];
I am attempting to create a UI programmatically. My problem is the view controllers subviews are not showing.
Here is how I am trying to create the UI:
.h
#import <UIKit/UIKit.h>
#protocol TimerCreatorDelegate <NSObject>
- (void)timerCreatorControllerDismissedWithString:(NSString *)timerName andTimeInterval:(NSTimeInterval)timeInterval;
#end
#interface TimerCreatorController : UIViewController {
// id timerCreatorDelegate;
}
#property (nonatomic, assign) id<TimerCreatorDelegate> timerCreatorDelegate;
#property (weak, nonatomic) UIDatePicker *timerLength;
#property (weak, nonatomic) UITextField *timerNameTextField;
#property (weak, nonatomic) UIButton *createTimerButton;
//#property (weak, nonatomic) IBOutlet UIDatePicker *timerLength;
//#property (weak, nonatomic) IBOutlet UITextField *timerNameTextField;
- (IBAction)createTimer:(id)sender;
#end
.m
#import "TimerCreatorController.h"
#interface TimerCreatorController ()
#end
#implementation TimerCreatorController
#synthesize timerCreatorDelegate;
#synthesize timerNameTextField;
#synthesize timerLength;
#synthesize createTimerButton;
- (void)viewDidLoad {
[super viewDidLoad];
self.view.backgroundColor = [UIColor grayColor];
timerNameTextField.placeholder = #"This timer is for:";
timerLength.datePickerMode = UIDatePickerModeCountDownTimer;
[createTimerButton setTitle:#"Start Timer" forState:UIControlStateNormal];
[createTimerButton setTitleColor:[UIColor colorWithRed:46/255 green:134/255 blue:53/255 alpha:1] forState:UIControlStateNormal];
createTimerButton.titleLabel.font = [UIFont fontWithName:#"HelveticaNeue-Light" size:20];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
/*
#pragma mark - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
// Get the new view controller using [segue destinationViewController].
// Pass the selected object to the new view controller.
}
*/
- (void)viewWillLayoutSubviews {
printf("viewWillLayoutSubviews Called.\n\n");
[self.view addSubview:timerLength];
[self.view addSubview:timerNameTextField];
[self.view addSubview:createTimerButton];
timerLength.translatesAutoresizingMaskIntoConstraints = false;
timerNameTextField.translatesAutoresizingMaskIntoConstraints = false;
createTimerButton.translatesAutoresizingMaskIntoConstraints = false;
timerLength.frame = CGRectMake(0, 0, self.view.frame.size.width, 216);
timerNameTextField.frame = CGRectMake((self.view.frame.size.width - 300) / 2, timerLength.frame.size.height + 40, 300, 30);
createTimerButton.frame = CGRectMake((self.view.frame.size.width - 96) / 2, timerNameTextField.frame.origin.y - 40, 96, 36);
[NSLayoutConstraint activateConstraints:[NSArray arrayWithObjects:
[timerLength.topAnchor constraintEqualToAnchor:self.view.topAnchor],
[timerLength.leftAnchor constraintEqualToAnchor:self.view.leftAnchor],
[timerLength.rightAnchor constraintEqualToAnchor:self.view.rightAnchor],
[timerLength.centerXAnchor constraintEqualToAnchor:self.view.centerXAnchor],
[timerNameTextField.topAnchor constraintEqualToAnchor:timerLength.bottomAnchor],
[timerNameTextField.rightAnchor constraintEqualToAnchor:self.view.rightAnchor constant:-37],
[timerNameTextField.leftAnchor constraintEqualToAnchor:self.view.leftAnchor constant:37],
// [timerNameTextField.heightAnchor constraintEqualToAnchor:NSLayoutAttributeNotAnAttribute constant:30],
[createTimerButton.centerXAnchor constraintEqualToAnchor:self.view.centerXAnchor],
// [createTimerButton.widthAnchor constraintEqualToAnchor:NSLayoutAttributeNotAnAttribute constant:96],
// [createTimerButton.heightAnchor constraintEqualToAnchor:NSLayoutAttributeNotAnAttribute constant:36],
[createTimerButton.topAnchor constraintEqualToAnchor:timerNameTextField.bottomAnchor]
#warning Finish Layout Constraints
, nil]];
NSString *timerLengthString = [NSString stringWithFormat:#"%#", NSStringFromCGRect(timerLength.frame)];
NSString *timerNameTextFieldString = [NSString stringWithFormat:#"%#", NSStringFromCGRect(timerNameTextField.frame)];
NSString *createTimerButtonString = [NSString stringWithFormat:#"%#", NSStringFromCGRect(createTimerButton.frame)];
printf("timerLength: %s \n", [timerLengthString UTF8String]);
printf("timerNameTextFieldString: %s \n", [timerNameTextFieldString UTF8String]);
printf("createTimerButtonString: %s \n", [createTimerButtonString UTF8String]);
}
- (IBAction)createTimer:(id)sender {
if ([self.timerCreatorDelegate respondsToSelector:#selector(timerCreatorControllerDismissedWithString:andTimeInterval:)]) {
[self.timerCreatorDelegate timerCreatorControllerDismissedWithString:timerNameTextField.text andTimeInterval:timerLength.countDownDuration];
}
[self dismissViewControllerAnimated:true completion:nil];
}
#end
Despite me setting the frames of my views, the prints are showing frames of {{0,0},{0,0}}.
Where do you create the subviews? I see you trying to use them, but not where you are actually creating the objects you are using. Is it a .Nib file or are you actually doing everything programmatically? And why are your subviews weak references? If they are not held by anything else they will be released after they are created...
In Swift it will crash when you try to use an object before it is initialized. Objective-C is a little more forgiving and will just do nothing if you tell it to use a nil object (at least in the instances you are using).
My custom UIView is not triggering this to run, but other custom views I make trigger it. Does anyone know the reason that this automatic refreshing of views would be triggered? Or Why "Refresh All Views" is greyed out.
Code is in here:
https://github.com/HannahCarney/HCRotaryWheel
Make sure you have IBInspectable properties for your view. (like
changing your view color,just to make sure your IBDesignable thing
works).
Make sure you have the code for your customisation in your view .m
file. (in your view draw rect method).
Make sure you provide the file owner name for your IBDesignable view.(in your storyboarD)
Make sure you mention IB_DESIGNABLE on your view .h file.
Finally a qucik clean and build of your storyboard,shall enable the
option of Refresh All views.
Sample code:
for view.h
#import <UIKit/UIKit.h>
IB_DESIGNABLE
#interface designalble_UIView : UIView
#property (nonatomic) IBInspectable UIColor *startColor;
#property (nonatomic) IBInspectable UIColor *midColor;
#property (nonatomic) IBInspectable UIColor *endColor;
#property (nonatomic) IBInspectable NSInteger borderWidth;
#property (nonatomic) IBInspectable CGFloat cornerRadious;
#property (nonatomic) IBInspectable BOOL isHorizontal;
#end
for view.m
#import "designalble_UIView.h"
#implementation designalble_UIView
- (instancetype)initWithFrame:(CGRect)frame {
self = [super initWithFrame:frame];
if (self) {
self.startColor = [UIColor redColor];
self.midColor = [UIColor greenColor];
self.endColor = [UIColor blueColor];
self.borderWidth = 2;
self.cornerRadious = 10;
self.isHorizontal = NO;
[self customInit];
}
return self;
}
- (id)initWithCoder:(NSCoder *)aDecoder {
self = [super initWithCoder:aDecoder];
if (self) {
[self customInit];
}
return self;
}
- (void)drawRect:(CGRect)rect {
[self customInit];
}
- (void)setNeedsLayout {
[super setNeedsLayout];
[self setNeedsDisplay];
}
- (void)prepareForInterfaceBuilder {
[self customInit];
}
- (void)customInit {
self.layer.cornerRadius = self.cornerRadious;
self.layer.borderWidth = self.borderWidth;
if (self.cornerRadious > 0) {
self.layer.masksToBounds = YES;
}
CAGradientLayer *gradient = [CAGradientLayer layer];
gradient.frame = self.bounds;
gradient.colors = [NSArray arrayWithObjects:(id)[self.startColor CGColor],(id)[self.midColor CGColor], (id)[self.endColor CGColor], nil];
gradient.endPoint = (self.isHorizontal) ? CGPointMake(1, 0) : CGPointMake(0, 1);
[self.layer insertSublayer:gradient atIndex:0];
}
I solved this because I had put IB_DESIGNABLE in the wrong spot in my code:
I had a protocol at the top of my view and previously it looked like
IB_DESIGNABLE
#protocol RotaryProtocol <NSObject>
- (void) wheelDidChangeValue:(int)currentSector;
#end
#interface HCRotaryWheel : UIView
#property (weak) id <RotaryProtocol> delegate;
#property (nonatomic, strong) IBInspectable UIColor* background;
#end
To fix this I had to move IB_DESIGNABLE below protocol
#protocol RotaryProtocol <NSObject>
- (void) wheelDidChangeValue:(int)currentSector;
#end
IB_DESIGNABLE
#interface HCRotaryWheel : UIView
#property (weak) id <RotaryProtocol> delegate;
#property (nonatomic, strong) IBInspectable UIColor* background;
#end
Now my views refresh!!
I have a problem with one of my views retaining its subviews. The main view displays 'tables' in a restaurant, and loads a subview to display this 'table'.
When the main view is deallocated, the tables seem to remain allocated to memory. I have searched everywhere to try and find a solution to this as I just can't seem to fix it myself.
Firstly the code for the 'table' view:
#protocol tableDelegate <NSObject>
#required
- (void)tablePress:(id)sender;
- (void)tableSelect:(id)sender;
#end
#interface tablevw : UIView
{
CGPoint currentPoint;
}
-(void)changeOrderImage;
-(id)initWithFrame:(CGRect)frame teststring:(NSString *)ts;
#property (nonatomic, weak) IBOutlet UIView *view;
#property (nonatomic, weak) IBOutlet UILabel *numberLabel;
#property (nonatomic, weak) IBOutlet UILabel *nameLabel;
#property (nonatomic) BOOL isEdit;
#property (nonatomic) BOOL hasOrder;
#property (nonatomic, strong) NSMutableDictionary * orderNumbers;
#property (nonatomic) int orderNumber;
#property (nonatomic, strong) NSString *teststring;
#property (nonatomic, weak) IBOutlet UIImageView *tableImage;
#property (nonatomic, weak) id<tableDelegate> delegate;
#end
And the init method for the view:
- (id)initWithFrame:(CGRect)frame teststring:(NSString *)ts{
self = [super initWithFrame:frame];
if (self) {
orderNumbers = [[NSMutableDictionary alloc]init];
isRemote = FALSE;
NSString *filePath = [[NSBundle mainBundle] pathForResource:#"tabletopRound" ofType:#"png"];
UIImageView * iV =[[UIImageView alloc] initWithImage:[[UIImage alloc] initWithContentsOfFile:filePath]];
self.tableImage= iV;
tableImage.frame = CGRectMake(0, 0, 121, 121);
locked = FALSE;
[self addSubview:tableImage];
UITapGestureRecognizer *doubleTapGestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:#selector(doubleTap)];
doubleTapGestureRecognizer.numberOfTapsRequired = 2;
[self addGestureRecognizer:doubleTapGestureRecognizer];
UILabel * label = [[UILabel alloc] initWithFrame:CGRectMake(35, 50, 48, 20)];
numberLabel = label;
[numberLabel setTextColor:[UIColor blackColor]];
[numberLabel setBackgroundColor:[UIColor clearColor]];
[numberLabel setText:ts];
[self addSubview:numberLabel];
UILabel * labelTwo = [[UILabel alloc] initWithFrame:CGRectMake(24, 123, 70, 20)];
nameLabel = labelTwo;
[nameLabel setTextColor:[UIColor whiteColor]];
[nameLabel setBackgroundColor:[UIColor clearColor]];
[self addSubview:nameLabel];
self.userInteractionEnabled = YES;
self.tag = [ts intValue];
}
return self;
}
Finally, in the 'main' view the tables are added like so:
NSString *myString = [results stringForColumn:#"table_number"];
tablevw * tableView = [[tablevw alloc] initWithFrame:CGRectMake(x-60.5, y-60.5, 121, 121) teststring:myString];
tableView.delegate = self;
[self.view addSubview: tableView];
The delegate is set to Nil when the main view is dealloced. I have over ridden the dealloc method to log the dealloc calls to me - it is being called on the 'main' view but not on the 'table' view.
Thanks for your help
In the dealloc method try
for (UIView *view in [self.view subviews]) {
[view removeFromSuperview];
}
It would be even better if u can try
[tablevw removeFromSuperview], tablevw = nil;
I can see that your tablevw has a week reference to his delegate and that should be enough for to release the parent, but just for argue sake trie to nil tablevws delegate. Create an array of tablevw instances you created (or tag them as already suggested), then before you release parent remove them from superview, set their delegate to nil and kill the array. See what happenes, maybe that will help...
I'm trying to move a point drawn in a UIView based on the value of a UISlider. The code below is for a UIView (subview ?) with a custom class (WindowView) on a UIViewController.
WindowView.h
#import <UIKit/UIKit.h>
#interface WindowView : UIView
- (IBAction)sliderValue:(UISlider *)sender;
#property (weak, nonatomic) IBOutlet UILabel *windowLabel;
#end
WindowView.m
#import "WindowView.h"
#interface WindowView ()
{
float myVal; // I thought my solution was using an iVar but I think I am wrong
}
#end
#implementation WindowView
#synthesize windowLabel;
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
// Initialization code
}
return self;
}
- (void)sliderValue:(UISlider *)sender
{
myVal = sender.value;
windowLabel.text = [NSString stringWithFormat:#"%f", myVal];
}
- (void)drawRect:(CGRect)rect
{
// I need to get the current value of the slider in drawRect: and update the position of the circle as the slider moves
UIBezierPath *circle = [UIBezierPath bezierPathWithOvalInRect:CGRectMake(myVal, myVal, 10, 10)];
[circle fill];
}
#end
OK, you need to store the slider value in an instance variable and then force the view to redraw.
WindowView.h:
#import <UIKit/UIKit.h>
#interface WindowView : UIView
{
float _sliderValue; // Current value of the slider
}
// This should be called sliderValueChanged
- (IBAction)sliderValue:(UISlider *)sender;
#property (weak, nonatomic) IBOutlet UILabel *windowLabel;
#end
WindowView.m (modified methods only):
// This should be called sliderValueChanged
- (void)sliderValue:(UISlider *)sender
{
_sliderValue = sender.value;
[self setNeedsDisplay]; // Force redraw
}
- (void)drawRect:(CGRect)rect
{
UIBezierPath *circle = [UIBezierPath bezierPathWithOvalInRect:CGRectMake(_sliderValue, _sliderValue, 10, 10)];
[circle fill];
}
You probably want to initialise _sliderValue to something useful in the view's init method.
Also _sliderValue probably isn't the name you want to choose; perhaps something like _circleOffset or some such.