How to access all labels in my view controller programmatically - ios

I am not sure is this even possible, but I will ask anyway.
This is my ViewController.h
#interface TBL_GameViewController : UIViewController
#property (strong, nonatomic) IBOutlet UILabel *roundText;
#property (strong, nonatomic) IBOutlet UILabel *roundNumber;
#property (strong, nonatomic) IBOutlet UILabel *playerText;
#property (strong, nonatomic) IBOutlet UILabel *playerScore;
#property (strong, nonatomic) IBOutlet UILabel *computerText;
#property (strong, nonatomic) IBOutlet UILabel *computerScore;
#end
And this is one method from .m file
- (void) lablesHiden:(BOOL)on
{
self.roundText.hidden = on;
self.roundNumber.hidden = on;
self.playerText.hidden = on;
self.playerScore.hidden = on;
self.computerText.hidden = on;
self.computerScore.hidden = on;
}
All this is working file.
Question
is the some way to a access all available labels in my view controller programmatically ?
Reason why I am asking this is:
I will have around 10 methods that will need access these labels, to change various properties (color, text, ...).
If tomorrow I add more label, I will also need add new label to all those methods and I would like to avoid that ?
UPDATE
I the end I used this approach
- (NSArray*) getAllLabels
{
NSArray *labels = [[NSArray alloc] initWithObjects:self.roundText, self.roundNumber, self.playerText, self.playerScore, self.computerText, self.computerScore, nil];
return labels;
}
- (void) appear:(BOOL)on
{
for (UILabel *label in [self getAllLabels]) {
label.alpha = 0.0;
}
// more code
}

There absolutely is a way:
for (id label in self.view.subviews) {
if ([label isKindOfClass:[UILabel class]]) {
// do your stuff...
}
}

You get more granular control about which labels to address by using tags. This is also cleaner than doing class introspection.
For example:
#define kPlayer 100
#define kRound 200
#define kComputer 300
#define kText 10
#define kNumber 20
You assign tags e.g. in viewDidLoad like this:
roundText.tag = kRound + kText;
Now there is no need to iterate through all subviews (you just have one iteration per transaction).
for (int x = 100; x < 400; x += 100) {
for (int y = 10; y < 30; y += 10) {
UILabel *label = (UILabel*) [self.view viewWithTag:x+y];
// do something with label
}
}
You can see that you can very conveniently exclude certain labels if you need to.
Also, via KVC, all labels can be accessed like this:
[self.view.subviews filteredArrayUsingPredicate:
[NSPredicate predicateWithFormat:#"tag > 99"]];

Related

Autolayout labels with UIView and Labels inside UIView

I am new to the autolayout thing, was trying to design the given screen for Compact Width|Regular Height via Storyboard. It seems Very simple cause there is none dynamic fields. I was following apple documentation, and setting constraints for each UIView. Its working fine if there would be no View(shown in purple color). But there is some requirement(have to hide the View based on star rating), thats why added this UIView containing dispatch details, complaint category, screenshot etc. e.g- For Invoice Number I set Top Space,Leading Space, Trailing Space and for the label(shown in green color) Top Space, Leading Space, Trailing Space so that height of invoice Number wouldn't be ambiguous rep, Repeated same for all Views. UIView(purple) constraints are Trailing Space to:SuperView, Bottom space to:SuperView, Bottom space to:Remarks Equals:15, Top Space Equals to:StarRating Equals:8. After that I have added constraints for the fields inside the purple View same as the other Views like Invoice Number. But not getting the desired result for different screen size. Any help would be much appreciated.
Use a UITableView to lay out this screen. You can use a static content table view, laid out entirely in the storyboard. Make the purple part its own section. In your UITableViewController subclass, you don't need to implement most data source / delegate methods (because you're using static content). Just override tableView:numberOfRowsInSection: to return 0 for the optional section if you don't want to show it, and use -[UITableView reloadSections:withRowAnimation;] to update the table view. Here's my test code:
#import "ViewController.h"
#interface ViewController ()
#property (strong, nonatomic) IBOutlet UITableViewCell *topMarginCell;
#property (strong, nonatomic) IBOutlet UIButton *star1;
#property (strong, nonatomic) IBOutlet UIButton *star2;
#property (strong, nonatomic) IBOutlet UIButton *star3;
#property (strong, nonatomic) IBOutlet UIButton *star4;
#property (strong, nonatomic) IBOutlet UIButton *star5;
#property (strong, nonatomic) NSArray<UIButton *> *starButtons;
#property (nonatomic) NSInteger rating;
#end
#implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
self.starButtons = #[ self.star1, self.star2, self.star3, self.star4, self.star5 ];
self.tableView.backgroundColor = self.topMarginCell.backgroundColor;
}
- (void)reloadDispatchSection {
[self.tableView reloadSections:[NSIndexSet indexSetWithIndex:1] withRowAnimation:UITableViewRowAnimationNone];
}
- (IBAction)starButtonWasTapped:(UIButton *)button {
NSInteger buttonIndex = [self.starButtons indexOfObject:button];
if (buttonIndex == NSNotFound) { return; }
self.rating = buttonIndex + 1;
[self.starButtons enumerateObjectsUsingBlock:^(UIButton * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
[obj setTitle:(idx <= buttonIndex ? #"★" : #"☆") forState:UIControlStateNormal];
}];
[self reloadDispatchSection];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
if (section == 1 && (self.rating == 0 || self.rating >= 4)) {
return 0;
} else {
return [super tableView:tableView numberOfRowsInSection:section];
}
}
#end
Result:

How to use the UIStepper to control global variable?

I tried to control the num variable through UIStepper, but when I pressed the increase button,
It always start count from 0 not 10,
I am curious what did I miss in my code,
Thank you in advance for any comments
#import "ViewController.h"
int num = 10;
#interface ViewController ()
#property (weak, nonatomic) IBOutlet UILabel *myLabel;
- (IBAction)myStepper:(UIStepper *)sender;
#end
#implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
_myLabel.text = [NSString stringWithFormat:#"%i", num];
}
- (IBAction)myStepper:(UIStepper *)sender {
num = [sender value];
_myLabel.text = [NSString stringWithFormat:#"%i", num];
}
#end
You're never setting the value of the stepper to num. Either set it in Interface Builder's Attributes Inspector, or create an outlet to your stepper:
#property (weak, nonatomic) IBOutlet UIStepper myStepper;
And then in -viewDidLoad, set it like this:
self.myStepper.value = num
As an aside, I would recommend against using a global variable. I would make a property for num instead.

Uncertain about public or private variable declaration and self delegate?

I'm very new to Objective-C and iOS development in general. This week I managed to get a small app running correctly in the simulator after large efforts.
I've pickup basics of the programming language by reading in "iOS 7 Programming Fundamentals" by Matt Neuburg, instructions from tutorials online and from suggestions on this website.
I've written code that works (apparently), but I do not fully understand why I needed to make several adjustments in my code to make it work.
The app is a basic one which solves a "wind triangle" for your information. All it needs to do, is putting some user defined variables in the correct formula, and display the outcome.
I've copied the .h and .m file. Simply said: the .h declares 7 variables; 5 user inputs in a textfield; 2 labels to display 2 calculated outcomes; one button which initiates the action to calculate.
With following code, I do not understand:
why I was forced to state my variables preceded by a underscore to use in the implementation
why I was forced to declare .delegate to 'self' for the variables after loading the view
Any suggestions to make this 'app' more logical and easier to understand (by myself) ?
//
// ViewController.h
// WindTriangle
//
#import <UIKit/UIKit.h>
#define M_PI 3.14159265358979323846264338327950288 /* pi */
float windDegreesFloat;
float windSpeedFloat;
float courseDesiredFloat;
float trueAirSpeedFloat;
float magneticVariationFloat;
float headingCalculatedFloat;
float groundSpeedCalculatedFloat;
#interface ViewController : UIViewController<UITextFieldDelegate>
#property (weak, nonatomic) IBOutlet UITextView *instructionsText;
#property (weak, nonatomic) IBOutlet UITextField *windDegrees;
#property (weak, nonatomic) IBOutlet UITextField *windSpeed;
#property (weak, nonatomic) IBOutlet UITextField *courseDesired;
#property (weak, nonatomic) IBOutlet UITextField *trueAirSpeed;
#property (weak, nonatomic) IBOutlet UITextField *magneticVariation;
#property (weak, nonatomic) IBOutlet UILabel *headingCalculated;
#property (weak, nonatomic) IBOutlet UILabel *groundSpeedCalculated;
- (IBAction)calculatePressed:(id)sender;
#end
And
//
// ViewController.m
// WindTriangle
//
#import "ViewController.h"
#interface ViewController ()
#end
#implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
self.windDegrees.delegate = self;
self.windSpeed.delegate = self;
self.courseDesired.delegate = self;
self.trueAirSpeed.delegate = self;
self.magneticVariation.delegate = self;
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (IBAction)calculatePressed:(id)sender {
windDegreesFloat = [_windDegrees.text floatValue];
windSpeedFloat = [_windSpeed.text floatValue];
courseDesiredFloat = [_courseDesired.text floatValue];
trueAirSpeedFloat = [_trueAirSpeed.text floatValue];
magneticVariationFloat = [_magneticVariation.text floatValue];
headingCalculatedFloat = ( courseDesiredFloat - magneticVariationFloat ) + ( 180 / M_PI ) * asin(( windSpeedFloat / trueAirSpeedFloat) * sin(( M_PI * ( windDegreesFloat - ( courseDesiredFloat - magneticVariationFloat))) / 180));
NSString * headingCalculatedString = [NSString stringWithFormat:#"%.1f", headingCalculatedFloat];
_headingCalculated.text = headingCalculatedString;
groundSpeedCalculatedFloat = sqrt(pow( trueAirSpeedFloat , 2) + pow(windSpeedFloat , 2) - (2 * trueAirSpeedFloat *windSpeedFloat * cos((M_PI * ( courseDesiredFloat - windDegreesFloat + ((180 / M_PI) * asin(( windSpeedFloat / trueAirSpeedFloat ) * sin((M_PI * ( windDegreesFloat - courseDesiredFloat )) / 180))))) / 180)));
NSString * groundSpeedCalculatedString = [NSString stringWithFormat:#"%.1f", groundSpeedCalculatedFloat];
_groundSpeedCalculated.text = groundSpeedCalculatedString;
}
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
return [textField resignFirstResponder];
}
#end
I'm brandnew to StackOverflow as well. Your comments will be much appreciated.
Hey so for your first question, the underscore indicates instance variables. Sometime back, you couldn't do this in objective c. If you declared a property, you had to call it through self.property after synthesizing it. So the underscore is just calling an instance.
As for the second question when you set the delegate in this case you're actually setting the delegate of the IBOutlet for the UITextField as the viewcontroller you're typing the code in. A delegate is responsible for the interaction between the controller and the view. This allows the view controller to manage certain methods of the UITextFieldDelegate
When you declare #property, for example:
#property (weak, nonatomic) UITextField *property;
Compiler create public variable, which you can access by self.property and private variable, which you access with underscore _property.
In your implementation you read private variable by adding underscore.
The delegate is a way for object to inform another object about something. In your example:
self.windDegrees.delegate = self;
self.windDegrees is a text field and this instruction means that this text field (windDegrees) will inform current class (ViewController) that something happened, for example method:
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
return [textField resignFirstResponder];
}
will be called every time your text fields should return.
You have several things wrong here. Your .h file should be:
//
// ViewController.h
// WindTriangle
//
#import <UIKit/UIKit.h>
#interface ViewController : UIViewController
#property (weak, nonatomic) IBOutlet UITextView *instructionsText;
#property (weak, nonatomic) IBOutlet UITextField *windDegrees;
#property (weak, nonatomic) IBOutlet UITextField *windSpeed;
#property (weak, nonatomic) IBOutlet UITextField *courseDesired;
#property (weak, nonatomic) IBOutlet UITextField *trueAirSpeed;
#property (weak, nonatomic) IBOutlet UITextField *magneticVariation;
#property (weak, nonatomic) IBOutlet UILabel *headingCalculated;
#property (weak, nonatomic) IBOutlet UILabel *groundSpeedCalculated;
- (IBAction)calculatePressed:(id)sender;
#end
You do not want to declare all of those unnecessary global variables. You do not need to redefine the standard M_PI macro. And you do not need to tell the world that your class conforms to the UITextField protocol.
In your .m file you should replace this:
#interface ViewController ()
#end
with:
#interface ViewController () <UITextViewDelegate, UITextFieldDelegate>
#end
Also, everywhere you reference one of the generated instance variables for one of your properties, you should change the reference to use the property instead. Example:
Change:
windDegreesFloat = [_windDegrees.text floatValue];
to:
windDegreesFloat = [self.windDegrees.text floatValue];
Do this everywhere you use the underscored variable instead of the property.
The use of self.windDegrees.delegate = self;, for example, is to tell the text field that your view controller (self) will be handling events from the text field.
Thanks for all the feedback. I changed the code with your feedback to following code.
As it worked before, it still does, but with correct(er) coding.
I'm starting to understand why I had to remove the global variables in .h, where to put correct protocol declarations, and also where the _ really stands for. Additional comments or thoughts are welcome. thx all !
//
// ViewController.h
// WindTriangle
//
#import <UIKit/UIKit.h>
#interface ViewController : UIViewController<UITextFieldDelegate>
#property (weak, nonatomic) IBOutlet UITextView *instructionsText;
#property (weak, nonatomic) IBOutlet UITextField *windDegrees;
#property (weak, nonatomic) IBOutlet UITextField *windSpeed;
#property (weak, nonatomic) IBOutlet UITextField *courseDesired;
#property (weak, nonatomic) IBOutlet UITextField *trueAirSpeed;
#property (weak, nonatomic) IBOutlet UITextField *magneticVariation;
#property (weak, nonatomic) IBOutlet UILabel *headingCalculated;
#property (weak, nonatomic) IBOutlet UILabel *groundSpeedCalculated;
- (IBAction)calculatePressed:(id)sender;
#end
And
//
// ViewController.m
// WindTriangle
//
#import "ViewController.h"
#interface ViewController () <UITextViewDelegate, UITextFieldDelegate>
#end
#implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
self.windDegrees.delegate = self;
self.windSpeed.delegate = self;
self.courseDesired.delegate = self;
self.trueAirSpeed.delegate = self;
self.magneticVariation.delegate = self;
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (IBAction)calculatePressed:(id)sender {
float windDegreesFloat = [self.windDegrees.text floatValue];
float windSpeedFloat = [self.windSpeed.text floatValue];
float courseDesiredFloat = [self.courseDesired.text floatValue];
float trueAirSpeedFloat = [self.trueAirSpeed.text floatValue];
float magneticVariationFloat = [self.magneticVariation.text floatValue];
float headingCalculatedFloat = ( courseDesiredFloat - magneticVariationFloat ) + ( 180 / M_PI ) * asin(( windSpeedFloat / trueAirSpeedFloat) * sin(( M_PI * ( windDegreesFloat - ( courseDesiredFloat - magneticVariationFloat))) / 180));
NSString * headingCalculatedString = [NSString stringWithFormat:#"%.1f", headingCalculatedFloat];
_headingCalculated.text = headingCalculatedString;
float groundSpeedCalculatedFloat = sqrt(pow( trueAirSpeedFloat , 2) + pow(windSpeedFloat , 2) - (2 * trueAirSpeedFloat *windSpeedFloat * cos((M_PI * ( courseDesiredFloat - windDegreesFloat + ((180 / M_PI) * asin(( windSpeedFloat / trueAirSpeedFloat ) * sin((M_PI * ( windDegreesFloat - courseDesiredFloat )) / 180))))) / 180)));
NSString * groundSpeedCalculatedString = [NSString stringWithFormat:#"%.1f", groundSpeedCalculatedFloat];
_groundSpeedCalculated.text = groundSpeedCalculatedString;
}
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
return [textField resignFirstResponder];
}
#end

Unrecognized selector sent to instance (UIStepper)

Okay, I know there is a ton of these questions out there, because I've looked and tried some of the solutions. However, many of the ones I tried didn't work or the answer was too over my head for me to really grasp well - I'm a new developer and this is my first app. I learn by learning what not to do at this point.
I have the 'unrecognized selector sent to instance error' on a UIStepper stepperValueChanged setup. Here is the contents of the error message as it is given to me:
[DetailViewController stepperValueChanged]: unrecognized selector sent to instance 0x8637630
I will probably be ripped apart for this, but I can't really understand what's going on here - my only guess so far is to assume it has something to do with the only point in my code where stepperValueChanged exists - under the DetailViewController.h, as placed below:
#interface DetailViewController : UIViewController <UISplitViewControllerDelegate>
{
// Create GUI parameters for text fields, text labels, and the stepper:
IBOutlet UITextField *value1;
IBOutlet UITextField *value2;
IBOutlet UITextField *value3;
IBOutlet UISwitch *double_precision;
IBOutlet UILabel *value1_type;
IBOutlet UILabel *value2_type;
IBOutlet UILabel *value3_type;
IBOutlet UILabel *deriv_units;
IBOutlet UILabel *units;
IBOutlet UILabel *result;
IBOutlet UIStepper *stepper;
}
// Define properties of the above GUI parameters:
#property (nonatomic, retain) UITextField *value1;
#property (nonatomic, retain) UITextField *value2;
#property (nonatomic, retain) UITextField *value3;
#property (nonatomic, retain) UILabel *value1_type;
#property (nonatomic, retain) UILabel *value2_type;
#property (nonatomic, retain) UILabel *value3_type;
#property (nonatomic, retain) UILabel *deriv_units;
#property (nonatomic, retain) UILabel *units;
#property (nonatomic, retain) UILabel *result;
// Setup property as instance of UIStepper:
#property (nonatomic, strong) IBOutlet UIStepper *stepper;
// Setup NSString instance for segue linking:
#property (nonatomic, strong) NSString *equationName;
#property (strong, nonatomic) id detailItem;
#property (weak, nonatomic) IBOutlet UILabel *detailDescriptionLabel;
// IBActions for the Calculate button and UIStepper instance:
- (IBAction)Calculate:(id)sender;
- (IBAction)stepperValueChanged:(id)sender;
- (IBAction)double_precision:(id)sender;
#end
Any ideas what is going on here? I don't have much of a clue, and if anyone can help explain to me what exactly is in play here while addressing it, I would be more than grateful.
If you need the contents of the implementation file, let me know; I'll edit it in.
Relevant areas of the .m file:
#interface DetailViewController ()
#property (strong, nonatomic) UIPopoverController *masterPopoverController;
- (void)configureView;
#end
#implementation DetailViewController
// Synthesize an instance of NSString for segue linking:
#synthesize equationName = _equationName;;
// Synthesize all other variables:
#synthesize value1 = _value1;
#synthesize value2 = _value2;
#synthesize value3 = _value3;
#synthesize value1_type = _value1_type;
#synthesize value2_type = _value2_type;
#synthesize value3_type = _value3_type;
#synthesize deriv_units = _deriv_units;
#synthesize result = _result;
#synthesize units = _units;
#synthesize stepper = _stepper;
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
[self configureView];
self.title = _equationName;
self.stepper.stepValue = 1;
self.stepper.autorepeat = NO;
self.stepper.continuous = YES;
self.stepper.wraps = YES;
int eqNum;
if ((_equationName = #"Energy-Frequency Relation"))
{
eqNum = 1;
self.stepper.minimumValue = 1;
self.stepper.maximumValue = 3;
}
else if ((_equationName = #"Energy-Frequency-Wavelength Relation"))
{
eqNum = 2;
self.stepper.minimumValue = 1;
self.stepper.maximumValue = 4;
}
// Take _equationName quantization and use it in a switch case to determine the formula that IBAction will use:
if (dflt)
{
switch (eqNum)
{
case 1:
if ((stepper.value = 1))
{
// Change deriv_units appropriately:
self.deriv_units.text = #"Energy (Joules)";
// This is a Planck's constant calculation, we hide the second variable as the constant
// is stored:
self.value2.hidden = YES;
self.value2_type.hidden = YES;
self.value3.hidden = YES;
self.value3_type.hidden = YES;
// Now we set up the parameters of the first entry variable:
self.value1_type.text = #"Frequency (in Hz)";
double frequency = [value1.text doubleValue];
double Planck = 6.626069e-34;
double energy = Planck * frequency;
// Now we set up the return field to return results:
NSString* resultIntermediate = [NSString stringWithFormat:#"%f", energy];
self.units.text = #"J";
}
// Identical function statements under ViewDidLoad truncated
}
bool dflt;
-(IBAction)KeyboardGoAway:(id)sender
{
[self.value1 resignFirstResponder];
[self.value1 resignFirstResponder];
[self.value1 resignFirstResponder];
}
-(IBAction)double_precision:(id)sender
{
// Sets double-float 'truth' value depending on state of UISwitch:
if (double_precision.on)
{
dflt = TRUE;
}
else
{
dflt = FALSE;
}
}
#pragma mark - Calculation runtime
-(IBAction)Calculate:(id)sender
{
// Assigns numerical information to _equationName data -
// switch case can only handle integer literals
// Also handles stepper incrementation and UILabel/UITextView hiding
NSString* resultIntermediate;
self.result.text = resultIntermediate;
}
The trailing colon makes the difference. Your action method is stepperValueChanged:,
but from the error message it seems that you connected the stepper to stepperValueChanged.
There are two reason for these kind of issues.
Probable case 1:
You first declared the function like - (IBAction)stepperValueChanged;
Connected the IBAction to stepper
Changed the method to - (IBAction)stepperValueChanged:(id)sender;
Solution:
Delete old connection in the interface builder and connect it again.
Probable case 2:
In your code you are calling the method using a selector where you written like: #selector(stepperValueChanged)
Solution:
Change the selector like: #selector(stepperValueChanged:)
Usually this means you are missing the method in your .m or you might of misspelled stepperValueChanged.
Edit: Actually, I believe it needs to be stepperValueChanged: with a semicolon.

Set slider value

i try to set a value to a slider after a button click,
but it does not work - the slider does not move. the code runs fine without mistakes.
It should be pretty simple but I can't figure it out.
xCode Version 4.5.2
Thanks!
here my code:
ViewController.h
#import <UIKit/UIKit.h>
#interface ViewController : UIViewController
#property (weak, nonatomic) IBOutlet UILabel *debugLabel;
#property (weak, nonatomic) IBOutlet UISlider *slider;
- (IBAction)slider:(id)sender;
- (IBAction)ButtonChangeValue:(id)sender;
#end
ViewController.m
#import "ViewController.h"
#interface ViewController ()
#end
#implementation ViewController
#synthesize slider;
...
- (IBAction)slider:(UISlider *)sender {
float value = [sender value];
self.debugLabel.text = [NSString stringWithFormat:#"Value: %f",value];
}
- (IBAction)ButtonChangeValue:(id)sender {
slider.value = 90;
}
I think your problem is that the slider accepts values between 0.0 and 1.0 (default values, change them with _slider.maximumValue and _slider.minimumValue). Try setting the value to 0.9 instead of setting 90 (if you mean 90%).
If the slider updates but is not animated, use :
[_slider setValue:0.9 animated:YES];
Note that given your code, you may need to use self.slider instead of _slider.
try using
self.slider.value = 90;
instead of
slider.value = 90;
Check My Answer
- (void)viewDidLoad
{
UITapGestureRecognizer *gr = [[UITapGestureRecognizer alloc] initWithTarget:self action:#selector(sliderTapped:)];
[slider addGestureRecognizer:gr];
}
- (void)sliderTapped:(UIGestureRecognizer *)g
{
UISlider* s = (UISlider*)g.view;
if (s.highlighted)
return; // tap on thumb, let slider deal with it
CGPoint pt = [g locationInView: s];
CGFloat percentage = pt.x / s.bounds.size.width;
CGFloat delta = percentage * (s.maximumValue - s.minimumValue);
CGFloat value = s.minimumValue + delta;
[s setValue:value animated:YES];
NSString *str=[NSString stringWithFormat:#"%.f",[self.slider value]];
self.lbl.text=str;
}
To use slider.value = 90;
Your ViewController.h should be:
#import <UIKit/UIKit.h>
#interface ViewController : UIViewController
{
UISlider *slider;
}
#property (weak, nonatomic) IBOutlet UILabel *debugLabel;
#property (weak, nonatomic) IBOutlet UISlider *slider;
- (IBAction)slider:(id)sender;
- (IBAction)ButtonChangeValue:(id)sender;
#end
And don't forget #synthesize slider; in your ViewController.m as well.
Otherwise, use self.slider.value = 90; or _slider.value = 90;
For Swift, you can use:
slider.setValue(5.0, animated: true)
Since you are using interface builder first thing to look at would be: are the UI components (slider, button) connected to the IBOutlets in File's owner. This is the most common source of problems like this.
Then check the min and max of the slider (default is 0;1 - as rdurand mentioned).
And spider1983 is correct also: since slider is a property, you can address it as self.slider (or _slider, but you shouldn't use the last one in this case).
i think . as you have not mentioned maximum and minimum value of slider ,it is taking default max and min values that are 0 to 1. So it is not possible to set value =90. First change its max and min like this :
Slider.minimumValue = 1;
Slider.maximumValue = 100;
now try your thing ,
Slider.value =90;
Within view
#State private var value1: Double = 0.9
Then make reference
Slider(value: $value1)

Resources