How to change a UILabel using a slider - ios

I'm new to objective c and I want to change a label text to the value of a slider.
Should I add some text first and should I add the UILabel inside the Action?
What I have is:
#import "slRootViewController.h"
#implementation slRootViewController {
NSMutableArray *_objects;
}
- (void)loadView {
[super loadView];
_objects = [[NSMutableArray alloc] init];
self.title = #"Slider Test ";
CGRect frame = CGRectMake(0.0, 0.0, 200.0, 10.0);
UISlider *slider = [[UISlider alloc] initWithFrame:frame];
[slider addTarget:self action:#selector(sliderAction:) forControlEvents:UIControlEventValueChanged];
[slider setBackgroundColor:[UIColor clearColor]];
slider.minimumValue = 0.0;
slider.maximumValue = 50.0;
slider.continuous = YES;
slider.value = 25.0;
UILabel *sliderText=[ [UILabel alloc] initWithFrame:CGRectMake(273,442,32,20)];
[self.view addSubview:slider];
[self.view addSubview:sliderText];
}
// voids
-(void)sliderAction:(id)sender
{
UISlider *slider = (UISlider*)sender;
self.sliderText.text=[NSString stringWithFormat:#"%f", slider.value];
//-- Do further actions
}
#end
But I'm getting an error saying
error: Use of undeclared identifier "sliderText"

Define the Label object Globally in your file.
#implementation slRootViewController {
NSMutableArray *_objects;
UILabel *sliderText; //Define globally label object
}
and change name or any activity for this label using globally object, like a
Change name,
sliderText.text = #"Set Name";
Set Text Color,
sliderText.textColor = [UIColor redColor];
and so on......

The error is due to the variable's scope. You are declaring sliderText inside loadView and finally accessing it in another method called sliderAction. It should be an instance variable (defined in either your .h or .m file depending on your needs). Just like you did with _objects.
#implementation slRootViewController {
NSMutableArray *_objects;
UILabel *sliderText; // Move it to your .h file if needed
}

It should be like this
#import "slRootViewController.h"
#implementation slRootViewController {
NSMutableArray *_objects;
}
#property (strong ,nonatomic) UILabel *sliderText;
- (void)loadView {
[super loadView];
_objects = [[NSMutableArray alloc] init];
self.title = #"Slider Test ";
CGRect frame = CGRectMake(60, 200.0, 200.0, 10.0);
UISlider *slider = [[UISlider alloc] initWithFrame:frame];
[slider addTarget:self action:#selector(sliderAction:) forControlEvents:UIControlEventValueChanged];
[slider setBackgroundColor:[UIColor clearColor]];
slider.minimumValue = 0.0;
slider.maximumValue = 50.0;
slider.continuous = YES;
slider.value = 25.0;
self.sliderText = [[UILabel alloc] initWithFrame:CGRectMake(60,CGRectGetMaxY(slider.frame)+40,120,20)];
//You can change y axis what you want
[self.view addSubview:slider];
[self.view addSubview:self.sliderText];
}
// voids
-(void)sliderAction:(id)sender
{
UISlider *slider = (UISlider*)sender;
self.sliderText.text=[NSString stringWithFormat:#"%f", slider.value];
//-- Do further actions
}

Let me clear with your error.
When you try to access any object in controller or class, which you haven't declared, or you declared in one method and you try to call its outside method (that's called as Out of Scope), then you will get an error like this.
Solutions:
1) Check your header file about the variable declaration.
2) Here you write self.sliderText. So make sure you have proper synthesize it.

You just need to change the UILabel declaration in implementation part..,just shown below in code
#import "slRootViewController.h"
#implementation slRootViewController {
NSMutableArray *_objects;
UILabel *sliderText; //<<---
}
- (void)loadView {
[super loadView];
_objects = [[NSMutableArray alloc] init];
self.title = #"Slider Test ";
CGRect frame = CGRectMake(0.0, 0.0, 200.0, 10.0);
UISlider *slider = [[UISlider alloc] initWithFrame:frame];
[slider addTarget:self action:#selector(sliderAction:) forControlEvents:UIControlEventValueChanged];
[slider setBackgroundColor:[UIColor clearColor]];
slider.minimumValue = 0.0;
slider.maximumValue = 50.0;
slider.continuous = YES;
slider.value = 25.0;
sliderText=[ [UILabel alloc] initWithFrame:CGRectMake(273,442,32,20)];
[self.view addSubview:slider];
[self.view addSubview:sliderText];
}
// voids
-(void)sliderAction:(id)sender
{
UISlider *slider = (UISlider*)sender;
sliderText.text=[NSString stringWithFormat:#"%f", slider.value];
}
#end

Related

Objective C UIButton with divider and changes textcolor when selected

I have created a row of UIButtons and added one week's date and day as UILabel on it. I have also created a UIView selector that when the button is selected, it will highlight the whole button.
Now I am stuck with how to add a separator or vertical lines between the buttons. And instead of highlighting the UIButton I wish to change the text colour to blue when the button is selected. Please help
What I have created
what i am trying to achieve
Code
CGFloat HEIGHT_BTN = 55.0; //--- 10 pixels from the navigation view
CGFloat HEIGHT_LABEL = 30.0;
CGFloat HEIGHT_LABEL2 = 15.0;
-(void)setupSegmentButtons
{
CGFloat Y_POS_BTN = [[UIApplication sharedApplication] statusBarFrame].size.height+5;
//=== The view where the buttons sits
navigationView = [[UIView alloc]initWithFrame:CGRectMake(0,Y_POS_BTN,self.view.frame.size.width,HEIGHT_BTN)];
navigationView.backgroundColor = [UIColor whiteColor];
[self.view addSubview:navigationView]; //=== Create a View called navigationView
//==== Setup the shadows
UIBezierPath *shadowPath = [UIBezierPath bezierPathWithRect:self.navigationView.bounds];
self.navigationView.layer.masksToBounds = NO;
self.navigationView.layer.shadowColor = [UIColor lightGrayColor].CGColor;
self.navigationView.layer.shadowOffset = CGSizeMake(5.0f, 5.0f);
self.navigationView.layer.shadowOpacity = 0.8f;
self.navigationView.layer.shadowPath = shadowPath.CGPath;
//=== Get the dates and formatting of the dates
NSDate *now = [NSDate date];
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDate *beginningOfThisWeek;
NSTimeInterval durationOfWeek;
[calendar rangeOfUnit:NSWeekCalendarUnit
startDate:&beginningOfThisWeek
interval:&durationOfWeek
forDate:now];
NSDateComponents *comps = [calendar components:NSUIntegerMax fromDate:now];
NSDateFormatter *dateFormatter=[[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"dd/MM/YYYY"];
NSDateFormatter *datelblFormat = [[NSDateFormatter alloc] init];
[datelblFormat setDateFormat:#"dd"];
NSDateFormatter *daylblFormat= [[NSDateFormatter alloc] init];
[daylblFormat setDateFormat:#"EEE"];
//=== Loop 7 times to create the Buttons and the 2 lines Labels
for (int i = 0; i<numControllers; i++) {
UIButton *button = [[UIButton alloc]initWithFrame:CGRectMake(i*(self.navigationView.frame.size.width/numControllers), 0, (self.navigationView.frame.size.width/numControllers),HEIGHT_BTN)];
[navigationView addSubview:button]; //=== Put the buttons into the navigation View
NSString *dateString = [dateFormatter stringFromDate:[calendar dateFromComponents:comps]];
[dtDate addObject:dateString];
NSString *lblDate = [datelblFormat stringFromDate:[calendar dateFromComponents:comps]];
firstLineButton = [[UILabel alloc] initWithFrame:CGRectMake(0,5,self.view.frame.size.width/numControllers,HEIGHT_LABEL)];
firstLineButton.text = lblDate;
firstLineButton.font = [UIFont systemFontOfSize:20];
firstLineButton.textColor = [UIColor whiteColor];
firstLineButton.textAlignment=NSTextAlignmentCenter;
[button addSubview:firstLineButton]; //=== Put the Date in the 1st line of the the button
NSString *lblDay = [daylblFormat stringFromDate:[calendar dateFromComponents:comps]];
UILabel *secondLineButton = [[UILabel alloc] initWithFrame:CGRectMake(0,28,self.view.frame.size.width/numControllers,HEIGHT_LABEL2)];
secondLineButton.text = lblDay;
secondLineButton.textColor = [UIColor whiteColor];
secondLineButton.font = [UIFont boldSystemFontOfSize:11];
secondLineButton.textAlignment=NSTextAlignmentCenter;
[button addSubview:secondLineButton]; //=== Put the Day in the 2nd line of the Button
button.tag = i; //--- IMPORTANT: if you make your own custom buttons, you have to tag them appropriately
button.backgroundColor = [UIColor colorWithRed:236.0f/255.0f green:0/255.0f blue:140.0f/255.0f alpha:0.6];//%%% buttoncolors
[button addTarget:self action:#selector(tapSegmentButtonAction:) forControlEvents:UIControlEventTouchUpInside];
++comps.day;
}
[self setupSelector]; //=== The selection bar or highligthed area
}
//=== sets up the selection bar under the buttons or the highligted buttons on the navigation bar
-(void)setupSelector {
//CGFloat Y_POS_BTN = [[UIApplication sharedApplication] statusBarFrame].size.height+5;
selectionBar = [[UIView alloc]initWithFrame:CGRectMake(0, Y_BUFFER, (self.view.frame.size.width/numControllers),HEIGHT_BTN)];
selectionBar.backgroundColor = [UIColor colorWithRed:236.0f/255.0f green:0/255.0f blue:140.0f/255.0f alpha:0.6]; //%%% sbcolor
//selectionBar.alpha = 0.8; //%%% sbalpha
[navigationView addSubview:selectionBar];
}
//=== When the top button is tapped
#pragma mark Setup
-(void)tapSegmentButtonAction:(UIButton *)button {
sDtDate = dtDate[button.tag];
[self LoadClasses];
__weak typeof(self) weakSelf = self;
[weakSelf updateCurrentPageIndex:button.tag];
NSInteger xCoor = selectionBar.frame.size.width*self.currentPageIndex;
selectionBar.frame = CGRectMake(xCoor, selectionBar.frame.origin.y, selectionBar.frame.size.width, selectionBar.frame.size.height);
}
Well, I'll prefer a more elegant way to achieve this.
First, create a UIButton subclass (let's say WeekdayButton) which will generate an attributed title from NSDate and configure so it is able to display a multiline title with different fonts.
WeekdayButton.h
#import <UIKit/UIKit.h>
#interface WeekdayButton : UIButton
#property (strong, nonatomic) NSDate *date;
#end
WeekdayButton.m
#import "WeekdayButton.h"
#implementation WeekdayButton
static NSDateFormatter *dayFormatter;
static NSDateFormatter *weekFormatter;
- (instancetype)initWithFrame:(CGRect)frame {
self = [super initWithFrame:frame];
[self setup];
return self;
}
- (void)awakeFromNib {
[super awakeFromNib];
[self setup];
}
- (void)setup {
self.titleLabel.numberOfLines = 2;
self.titleLabel.lineBreakMode = NSLineBreakByWordWrapping;
self.titleLabel.textAlignment = NSTextAlignmentCenter;
self.backgroundColor = [UIColor colorWithRed:236.0f/255.0f green:0/255.0f blue:140.0f/255.0f alpha:0.6];
}
- (void)setDate:(NSDate *)date {
_date = date;
NSAttributedString *normalTitle = [self generateNormalTitle];;
NSAttributedString *selectedTitle = [self generateSelectedTitle];
[self setAttributedTitle:normalTitle forState:UIControlStateNormal];
[self setAttributedTitle:selectedTitle forState:UIControlStateSelected];
}
- (NSAttributedString *)generateNormalTitle {
NSMutableAttributedString *result = [NSMutableAttributedString new];
if (!dayFormatter) {
dayFormatter = [NSDateFormatter new];
dayFormatter.dateFormat = #"dd";
}
if (!weekFormatter) {
weekFormatter = [NSDateFormatter new];
weekFormatter.dateFormat = #"EEE";
}
NSString *day = [[dayFormatter stringFromDate:self.date] stringByAppendingString:#"\n"];
NSString *week = [weekFormatter stringFromDate:self.date];
[result appendAttributedString:[[NSAttributedString alloc] initWithString:day
attributes:#{NSFontAttributeName:[UIFont systemFontOfSize:20]}]];
[result appendAttributedString:[[NSAttributedString alloc] initWithString:week
attributes:#{NSFontAttributeName:[UIFont boldSystemFontOfSize:11]}]];
[result addAttribute:NSForegroundColorAttributeName value:[UIColor whiteColor] range:NSMakeRange(0, result.length)];
return result;
}
- (NSAttributedString *)generateSelectedTitle {
NSMutableAttributedString *result = [[self generateNormalTitle] mutableCopy];
[result addAttribute:NSForegroundColorAttributeName value:[UIColor blueColor] range:NSMakeRange(0, result.length)];
return result;
}
#end
Then in your ViewController make a horizontal UIStackView, generate 7 WeekdayButton button and pass NSDate object starting from today.
ViewController.m
#import "ViewController.h"
#import "WeekdayButton.h"
#interface ViewController ()
#property (strong, nonatomic) UIStackView *stackView;
#end
#implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
[self setupWeekDayButtons];
}
- (void)setupWeekDayButtons {
UIView *containerView = [[UIView alloc] initWithFrame:CGRectMake(0, 40, self.view.frame.size.width, 55)];
containerView.autoresizingMask = UIViewAutoresizingFlexibleWidth;
[self.view addSubview:containerView];
containerView.layer.shadowRadius = 5;
containerView.layer.shadowColor = [UIColor blackColor].CGColor;
containerView.layer.shadowOpacity = 0.5;
containerView.layer.shadowOffset = CGSizeMake(0, 5);
self.stackView = [[UIStackView alloc] initWithFrame:containerView.bounds];
self.stackView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
self.stackView.axis = UILayoutConstraintAxisHorizontal;
self.stackView.distribution = UIStackViewDistributionFill;
self.stackView.spacing = 0;
[containerView addSubview:self.stackView]; //Embeding stackview in a UIView cause UIStackView can't draw shadow.
int numberOfDays = 7;
for (int i = 0; i < numberOfDays; i++) {
NSDate *date = [[NSDate date] dateByAddingTimeInterval:i * 24 * 3600];
WeekdayButton *button = [WeekdayButton buttonWithType:UIButtonTypeCustom];
[button addTarget:self action:#selector(weekDayTapped:) forControlEvents:UIControlEventTouchUpInside];
button.date = date;
button.translatesAutoresizingMaskIntoConstraints = NO;
[self.stackView addArrangedSubview:button];
[button.widthAnchor constraintEqualToAnchor:self.stackView.widthAnchor
multiplier:1/(CGFloat)numberOfDays].active = YES;
if (i != numberOfDays - 1) {
UIView *separator = [UIView new];
separator.translatesAutoresizingMaskIntoConstraints = NO;
separator.backgroundColor = [UIColor whiteColor];
[button addSubview:separator];
[separator.widthAnchor constraintEqualToConstant:1].active = true;
[separator.trailingAnchor constraintEqualToAnchor:button.trailingAnchor constant:0].active = YES;
[separator.centerYAnchor constraintEqualToAnchor:button.centerYAnchor constant:0].active = YES;
[separator.heightAnchor constraintEqualToAnchor:button.heightAnchor multiplier:1 constant:-20].active = YES;
}
}
}
- (void)weekDayTapped:(WeekdayButton *)sender {
[self.stackView.arrangedSubviews makeObjectsPerformSelector:#selector(setSelected:) withObject:nil]; //Deselecting all buttons
sender.selected = YES;
NSLog(#"Selected: %#", sender.date);
//TODO: Do your logic after selection here
}
#end
Here is the result:
I here provide an answer with the power of stack view and auto layout
The code will be limited and you can customized almost everything in IB.
Tint color of buttons may needs care when setting selected state.
-(IBAction)selector:(id)sender{
UIButton * button = (UIButton *)sender;
[button setSelected: !button.isSelected ];
}
setting in IB
selected State
topstackview
second stack view
Use this idea, you can build your example much faster and safe.
For: "how to add a separator or vertical lines between the buttons":
After [button addSubview:secondLineButton]; //=== Put the Day in the 2nd line of the Button add a view as separator
if (i < (numControllers - 1)){
UIView *separator = [[UIView alloc] initWithFrame:CGRectMake(button.frame.size.width - 1, 5, 1, button.frame.size.height - 10))];
separator.backgroundColor = UIColor.whiteColor
[button addSubview:separator];
}
For text color, create: btnCurrentSelected and:
#interface YouClass : UIViewController
{
UIButton *btnCurrentSelected;
}
-(void)tapSegmentButtonAction:(UIButton *)button {
sDtDate = dtDate[button.tag];
[self LoadClasses];
[btnCurrentSelected setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal] // set color for old button selected
btnCurrentSelected = button
[btnCurrentSelected setTitleColor:[UIColor blueColor] forState:UIControlStateNormal] // set color for button selected
__weak typeof(self) weakSelf = self;
[weakSelf updateCurrentPageIndex:button.tag];
NSInteger xCoor = selectionBar.frame.size.width*self.currentPageIndex;
selectionBar.frame = CGRectMake(xCoor, selectionBar.frame.origin.y, selectionBar.frame.size.width, selectionBar.frame.size.height);
}
You don't need to use UIButton here, just need to customize a UIControl subclass where the needed customize layout inside, you need to handle highlighting Or general state inside the selected Set method

How to delete UITextfield and entered data from it in iOS

I have develop one application and in that I have two UIButton named [+] and [-] and one UITextField default.
Now what I want is when I click on plus [+] button it should add one UITextField in UIView that is work perfectly to me but when I click on minus [-] button it should delete last created UITextField that is not working now for me.
How to manage that?
here is my code to plus[+] button.
- (IBAction)btnPlusClicked:(id)sender
{
scrollViewSpecialitiesTxtFields.hidden = FALSE;
float y;
y = (35 * txtSpecialityFieldCounter);
UITextField *textField = [[UITextField alloc] initWithFrame:CGRectMake(0, y, 120, 30)];
textField.delegate = self;
textField.borderStyle = UITextBorderStyleRoundedRect;
[arraySpecialitiesTxtFields insertObject:textField atIndex:arraySpecialitiesTxtFields.count];
scrollViewSpecialitiesTxtFields.contentSize = CGSizeMake(125, y+30);
[scrollViewSpecialitiesTxtFields addSubview:textField];
txtSpecialityFieldCounter++;
NSLog(#"txtSpecialityFieldCounter : %d",txtSpecialityFieldCounter);
}
here is my minus [-] button code
-(IBAction)btnMinusClicked:(id)sender
{
[scrollViewSpecialitiesTxtFields.subviews makeObjectsPerformSelector:#selector(removeFromSuperview)];
txtSpecialityFieldCounter--;
NSLog(#"txtSpecialityFieldCounter : %d",txtSpecialityFieldCounter);
float y;
y = (35 * txtSpecialityFieldCounter);
for(int i = 0 ; i < txtSpecialityFieldCounter; i++)
{
UITextField *textField = [[UITextField alloc] initWithFrame:CGRectMake(0, y, 120, 30)];
textField.delegate = self;
textField.borderStyle = UITextBorderStyleRoundedRect;
[arraySpecialitiesTxtFields insertObject:textField atIndex:arraySpecialitiesTxtFields.count];
scrollViewSpecialitiesTxtFields.contentSize = CGSizeMake(125, y-30);
[scrollViewSpecialitiesTxtFields addSubview:textField];
}
}
I know minus[-] button code is wrong but let me know changes
Create a global variable as NSMutableArray *myAddedTextfields and in viewDidLoad-> myAddedTextFields = [NSMutableArray array];
- (IBAction)plusAction:(id)sender
{
UITextField *textField1 = [[UITextField alloc]initWithFrame:CGRectMake(50, 50, 100, 20)];
textField1.text = #"hey how r u";
textField1.backgroundColor = [UIColor grayColor];
textField1.tag = 1;
[self.view addSubview:textField1];
[myAddedTextFields addObject:textField1];
}
- (IBAction)minusAction:(id)sender
{
UITextField *txtField = [myAddedTextFields objectAtIndex:myAddedTextFields.count -1]; //for deleting from the last textfield onwards.
[txtField removeFromSuperView];
[myAddedTextFields removeObjectIdenticalTo:txtField];
}
I have edited your method.. hope this helps.
Whenever you want to add an UITextField on a superview, set the tag of that component (UITextField).
And when you want to remove it from superview then get the reference of that component (UITextField) using the tag and remove it from the superview.
Here is an example that may be helpful to you:
-(IBAction)plusAction:(id)sender
{
UITextField *textField1 = [[UITextField alloc]initWithFrame:CGRectMake(50, 50, 100, 20)];
textField1.text = #"hey how r u";
textField1.backgroundColor = [UIColor grayColor];
textField1.tag = 1;
[self.view addSubview:textField1];
}
-(IBAction)minusAction:(id)sender
{
UITextField * textfield = (UITextField *)[self.view viewWithTag:1];
[textfield removeFromSuperview];
}
Yes, you could use the tag option. Or you could use an NSArray holding your UITextFields.
#interface MyTextFieldViewClass ()
#property (nonatomic, retain) NSMutableArray *textFields;
#end
#implementation MyTextFieldViewClass
- (void)viewDidLoad {
[super viewDidLoad];
self.textFields = [NSMutableArray array];
}
- (IBAction)addTextField:(id)sender {
UITextField *tf = [[UITextField alloc] initWithFrame:CGRectMake(50, 50, 100, 20)];
[self.textFields addObject:tf];
[self.view addSubview:tf];
}
- (IBAction)removeTextField:(id)sender {
UITextField *tf = [self.textFields lastObject];
[tf removeFromSuperview];
[self.textFields removeLastObject];
}
#end
This would be a little better since you do not have to iterate over all the views/ids that exist in self.view.subviews. Also, using the tag might not be reliable since you always want to remove the last item, so you would either need to keep the last item number in memory or you need to iterate over all the subviews in order to find the UITextField with the highest tag and in order to remove it.

incompatible pointer types assigning to uilabel from label view

i've been doing a thing here using objective-c, but i'm a beginner in this language, and that's what i did:
I've created two UIView class and named them as LabelView and ButtonView. What i wanted to do is when i touch the button the label text changes. I have given the code below which i did.
I get an error when i touch the button i've created.
Error: "-[LabelView setText:]: unrecognized selector sent to instance 0x7b66cf80"
Warning on the line: self.cslbl_ = lblView; -
"incompatible pointer types assigning to uilabel from label view".
- (void)viewDidLoad {
LabelView *lblView = [[LabelView alloc] init];
[lblView setFrame:CGRectMake(10, 100, 300, 50)];
//lblView.backgroundColor = [UIColor redColor];
self.cslbl_ = lblView;
[self.view addSubview:lblView];
ButtonView *btnView = [[ButtonView alloc] initWithFrame:CGRectMake(110, 200, 100, 50)];
SEL target = #selector(changeText:);
[btnView setSelector:self selector:target];
[self.view addSubview:btnView];
}
-(void) changeText:(UIButton *)btn {
static int k = 0;
if (k%2 == 0)
{
[self.cslbl_ setText:#"Apple is a healthy fruit"];
}
else
{
[self.cslbl_ setText:#"Apple"];
}
NSLog(#"Click value is %d",k);
k++;
}
Custom Label Class
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self)
{
UILabel *myLbl = [[UILabel alloc] init];
myLbl.frame = CGRectMake(0, 0, 300, 50);
//myLbl.backgroundColor = [UIColor blueColor];
myLbl.text = #"Apple";
self.lbl_ = myLbl;
[self addSubview:myLbl];
}
return self;
}
Custom Button Class
-(id) initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self)
{
UIButton *myBtn = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, 100, 50)];
[myBtn setTitle:#"Touch" forState:UIControlStateNormal];
[myBtn setTitle:#"Touched" forState:UIControlStateHighlighted];
myBtn.backgroundColor = [UIColor grayColor];
self.btn_ = myBtn;
[self addSubview:myBtn];
}
return self;
}
- (void)setSelector:(UIViewController *)vc selector:(SEL)changeText
{
[btn_ addTarget:vc action:changeText forControlEvents:UIControlEventTouchUpInside];
}
Though question is not clear but it seems that your self.cslbl_ is a UILabel and you are assigning lblView to it which of type UIView, thats the reason you are getting warning.
And you are trying to setText to LabelView which is again not a UILabel type that why you are getting crash.
First of all you LabelView should be a subclass of UILabel not UIView but still if its your requirement then you should use below code.
Custom Label Class
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self)
{
UILabel *myLbl = [[UILabel alloc] init];
myLbl.frame = CGRectMake(0, 0, 300, 50);
[myLb1 setTag:1];
//myLbl.backgroundColor = [UIColor blueColor];
myLbl.text = #"Apple";
self.lbl_ = myLbl;
[self addSubview:myLbl];
}
return self;
}
in viewdidload
LabelView *lblView = [[LabelView alloc] init];
[lblView setFrame:CGRectMake(10, 100, 300, 50)];
self.cslbl_ = (UILabel*)[lblView viewWithTag:1];
[self.view addSubview:lblView];
Now you can set text to your self.cslbl_

I want my UILabel to follow my UISlider value

I follow the code of user2207904
on viewDidLoad I create 20 sliders and 20 labels
then my 20 labels take the values of my faders (label.text= [NSString stringWithFormat:#"%i", slvalue];)
but like this if I move my labels don't follows my faders values...
how can I do to my labels follows my faders values?
MY CODE
- (void)viewDidLoad
{
[super viewDidLoad];
for(int i=0; i< 20; i++){
//sliders
UISlider *slider = [[[UISlider alloc] initWithFrame:CGRectMake(1+i*50, 450, 300, 10)] autorelease];
slider.minimumValue = 1;
slider.maximumValue = 100;
slider.continuous = YES;
[self.view addSubview:slider];
slider.transform = CGAffineTransformRotate(slider.transform, 270.0/180*M_PI);
[slider setThumbImage:thumbImage0 forState:UIControlStateNormal];
[slider release];
// label
UILabel *label = [[UILabel alloc] initWithFrame: CGRectMake(1+i*50, 640, 40, 15)];
int slvalue = slider.value;
label.text= [NSString stringWithFormat:#"%i", slvalue];
[self.view addSubview:label];
[label release];
}
New issue :
mofified
I do this :
i put an IBAction in my FirstViewController.m
- (IBAction)sliderUpdate:(UISlider *)sender {
self.label.text = [NSString stringWithFormat:#"%g", sender.value];
}
and put this in my viewDidLoad (FirstViewController.m)
{
[super viewDidLoad];
for(int i=0; i< 20; i++){
//sliders
UISlider *slider = [[[UISlider alloc] initWithFrame:CGRectMake(1+i*50, 450, 300, 10)] autorelease];
slider.minimumValue = 1;
slider.maximumValue = 100;
slider.continuous = YES;
[slider addTarget:self action:#selector(sliderUpdate:) forControlEvents:UIControlEventValueChanged];
[self.view addSubview:slider];
slider.transform = CGAffineTransformRotate(slider.transform, 270.0/180*M_PI);
[slider setThumbImage:thumbImage0 forState:UIControlStateNormal];
[slider release];
// label
UILabel *label = [[UILabel alloc] initWithFrame: CGRectMake(1+i*50, 640, 40, 15)];
int slvalue = slider.value;
label.text= [NSString stringWithFormat:#"%i", slvalue];
[self.view addSubview:label];
[label release];
}
i have this error in my (IBAction)sliderUpdate: Property 'label' not found on object of type 'FirstViewController *'
If you control drag from a slider to the implementation of your UIViewController, it will set up an IBAction method that is called whenever the value is changed. In this method, simply set the text of your label. No need to make a special subclass.
The code will end up looking something like this:
- (IBAction)setLabel:(UISlider *)sender {
self.myLabel.text = [NSString stringWithFormat:#"%g", sender.value];
}
EDIT: It sounds like you are making the sliders programmatically. In that case, you're going to have to call addTarget:action:forControlEvents: on each one to set up the target-action. (The control event will be UIControlEventValueChanged.)
Also, as far as knowing what slider goes to what label, you could make 2 NSArrays in which the ith slider in one array matches the ith label in the other array.
Drag and drop or programetically create one UILabel and UISlider ,then in the Slider use this for slider action
-(IBAction)slider:(id)sender {
NSString *s=[NSString stringWithFormat:#"%f",slider.value];
[label setText:s]; }
So whenever you change your slider your label value also changes.I hope you got it ryt?

UIView with rounded corners: I've forgotten something

I'm developing an iOS application with latest SDK.
I have this custom UIView:
#define ANNOTATION_WIDTH 250
#define ANNOTATION_HEIGHT 200
#implementation CustomView
- (id)initwithTitle:(NSString* )title subTitle:(NSString* )subTitle
{
CGRect annotationFrame =
CGRectMake(10, 10, ANNOTATION_WIDTH, ANNOTATION_HEIGHT);
if ([self initWithFrame:annotationFrame])
{
self.backgroundColor = [UIColor redColor];
self.opaque = YES;
/*
UILabel* nameLabel =
[[UILabel alloc] initWithFrame:CGRectMake(0, 0, ANNOTATION_WIDTH, 20.0)];
nameLabel.backgroundColor = [UIColor whiteColor];
nameLabel.textAlignment = NSTextAlignmentCenter;
//nameLabel.text = coordinate.name;
nameLabel.text = title;
[nameLabel sizeToFit];
[nameLabel setFrame: CGRectMake(0,
0,
nameLabel.bounds.size.width + 8.0,
nameLabel.bounds.size.height + 8.0)];
[self addSubview:nameLabel];
UILabel* placeLabel =
[[UILabel alloc] initWithFrame:CGRectMake(25, 0, ANNOTATION_WIDTH, 20.0)];
placeLabel.backgroundColor = [UIColor whiteColor];
placeLabel.textAlignment = NSTextAlignmentCenter;
//placeLabel.text = coordinate.place;
placeLabel.text = subTitle;
[placeLabel sizeToFit];
[placeLabel setFrame:CGRectMake(25,
0,
placeLabel.bounds.size.width + 8.0,
placeLabel.bounds.size.height + 8.0)];
[self addSubview:placeLabel];
*/
}
return self;
}
I will show a title and a subTitle, but now that code is comment because I'm testing something.
To add this custom view to an UIViewController I do this:
#import "ViewController.h"
#import "CustomView.h"
#import <QuartzCore/QuartzCore.h>
#implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
CustomView* cView = [[CustomView alloc] initwithTitle:#"Titulo" subTitle:#"Subtitulo"];
cView.layer.cornerRadius = 10;
cView.layer.masksToBounds = YES;
[self.view addSubview:cView];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#end
If I don't show title and subTitle and I don't see my customView, but I show title and subTitle I only see rounded upper left corner.
I have tried this also, and it doesn't work:
CustomView* cView = [[CustomView alloc] initwithTitle:#"Titulo" subTitle:#"Subtitulo"];
cView.layer.cornerRadius = 10;
cView.clipsToBounds = YES;
Is there any way to show a UIView with rounded corners without adding any subview?
I don't know what it is happening and Id on't know why I get rounded upper left corner only.
Try this:
cView.layer.cornerRadius = 10.0f;
cView.layer.masksToBounds = YES;
cView.layer.opaque = NO;
[self.view addSubview:cView];
are you tried this
[self.layer setCornerRadius:10];
[self.layer setMasksToBounds:YES];

Resources