How to get a certain subview from UIView by tag - objective-c

I'm a noob in Objective-C and I have one question.
I have one UILabel object that I adding to one UIView with this code:
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0,10,self.view.frame.size.width-15-70, 30)];
label.tag = 1;
label.font = [PublicObject fontTexts:17];
label.textAlignment = NSTextAlignmentRight;
label.textColor = [UIColor whiteColor];
[cell setBackgroundColor:[UIColor clearColor]];
UIView *view = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 320, 50)];
view.backgroundColor = [PublicObject colorWithHexString:#"cd4110"];
label.text = [filterData objectAtIndex:indexPath.row];
view addSubview:label];
Now I want get one subview in my view where this subview has tag = 1 and save it on another object like this:
UILabel *tagLabel;
tagLabel = // I want get one subview in view where tag = 1
Please help me understand how to do this.

Example with UILabel:
UILabel *label = (UILabel *)[self.view viewWithTag:1];
good luck!

You can get your subviews with for loop iteration
for (UIView *i in self.view.subviews){
if([i isKindOfClass:[UILabel class]]){
UILabel *newLbl = (UILabel *)i;
if(newLbl.tag == 1){
/// Write your code
}
}
}
Swift
let label:UILabel = self.view.viewWithTag(1) as! UILabel

You can get the subview with the code which others have mentioned, just like
UILabel *tagLabel = (UILabel*)[view viewWithTag:1];
But an important point to remember,
Make sure the parent view doesn't have the same tag value as of the subview. Otherwise the viewWithTag: method will return the receiver view (on which you are calling viewWithTag:) instead of returning the actual subview you want.
So keep the parent view and child views tags distinct whenever you need to use viewWithTag:.

Swift 3, Swift 4 and Swift 5
if let subLabel: UILabel = primaryView.viewWithTag(123) as? UILabel {
subLabel.text = "do things here :-D"
}

You could use the viewWithTag: method.

If you are on the same view
UILabel *tagLabel = (UILabel*)[view viewWithTag:1];
Also, if you want a new instance of UILabel
UILabel *newTagLabel = [tagLabel copy];
//customize new label here...
[view addSubView:newTagLabel];

Related

Unable to set rightview or leftview in textfield of searchbar in ios 7

Purpose:
I want to set right view as label in searchbar's textfield
Following Code working fine in ios 6 for doing the same thing:
UISearchBar *search = [[UISearchBar alloc] init];
[search setTintColor:[UIColor grayColor]];
search.frame = CGRectMake(0, 150, 320,50);
search.delegate = self;
UITextField *searchField=[search.subviews objectAtIndex:1];//Changed this line in ios 7
searchField.backgroundColor=[UIColor redColor];
UILabel *label=[[UILabel alloc] initWithFrame:CGRectMake(0, 0, 40, 40)];
label.text=#"Hello";
label.textColor=[UIColor greenColor];
searchField.rightView = label;
searchField.rightViewMode = UITextFieldViewModeAlways;
[self addSubView:search];
When i have Run the same code in ios 7(with xcode 7.0.2 fully updated), It was giving me error, after googling i got that hiearchy of searchbar to textfield has been changed, so i have modified my code as:
replaced commented line in above code with:
UITextField *searchField=[((UIView *)[search.subviews objectAtIndex:0]).subviews lastObject];
after doing this, it is not giving me any error(also checked the logs by printing the description of textfield and everything is working good), when i run it, it gives textfield with red background but the rightView's label is not shown to me. Now, can anyone help me how to show this rightview.
If you want to do this programatically then you have to declare UISearchBar object in your .h file.
UISearchBar *searchBar;
And in your .m file you can code like:
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
searchBar = [[UISearchBar alloc] init];
[searchBar setTintColor:[UIColor grayColor]];
searchBar.frame = CGRectMake(0, 150, 320,50);
searchBar.delegate = self;
[self.view addSubview:searchBar];
}
- (void)viewDidAppear:(BOOL)animated {
[super viewDidAppear:animated];
UITextField *searchField;
if ([[[UIDevice currentDevice] systemVersion] floatValue]<7.0)
searchField=[searchBar.subviews objectAtIndex:1];
else
searchField=[((UIView *)[searchBar.subviews objectAtIndex:0]).subviews lastObject];
searchField.backgroundColor=[UIColor redColor];
UILabel *label=[[UILabel alloc] initWithFrame:CGRectMake(0, 0, 40, 40)];
label.text=#"Hello";
label.textColor=[UIColor greenColor];
searchField.rightView = label;
searchField.rightViewMode = UITextFieldViewModeAlways;
}
I think this will work for both iOS7 and prior versions of iOS7.
First of all, your approach is not good and not maintainable across iOS versions.
I think that initialization of UISearchBarTextField's right view is taking place after you set your custom view to it's rightView property. You will see correct result if you set searchField.rightView in viewDidAppear method:
- (void)viewDidAppear:(BOOL)animated {
[super viewDidAppear:animated];
UITextField *searchField=[((UIView *)[_searchBar.subviews objectAtIndex:0]).subviews lastObject];
UILabel *label=[[UILabel alloc] initWithFrame:CGRectMake(0, 0, 40, 40)];
label.text=#"Hello";
label.textColor=[UIColor greenColor];
searchField.rightView = label;
searchField.rightViewMode = UITextFieldViewModeAlways;
}
I've tested it on iOS 7 simulator and it works.
You have to get the text field first.
No need to index subviews to get text field or bar button.
You can directly get the text field and bar button
In swift
let textField = searchBar.valueForKey("searchField") as? UITextField
let cancelBarButton = searchBar.valueForKey("cancelBarButtonItem") as? UIBarButtonItem
In Objective-C
UITextField *textField = [searchBar valueForKey:#"searchField"]:
UIBarButtonItem *cancelBarButton = [searchBar valueForKey:#"cancelBarButtonItem"]:
Then you can set the left view and right view with
textField.leftView = yourView
textField.rightView = yourView

my UITableViewCell setting button

I'm having trouble adding button to my UITableViewCell, the cell has two UILabels and two UIImageViews, sometimes the UIImageView will contain an image and sometimes a button:
In my UITableViewCell subclass I have:
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if ( self ) {
// Initialization code
firstLock = [[UILabel alloc]init];
[firstLock setBackgroundColor:[UIColor clearColor]];
firstLock.textAlignment = UITextAlignmentLeft;
firstLock.font = [UIFont fontWithName:#"Arial-BoldMT" size:17];
secondLock= [[UILabel alloc]init];
[secondLock setBackgroundColor:[UIColor clearColor]];
secondLock.textAlignment = UITextAlignmentRight;
secondLock.font = [UIFont fontWithName:#"Arial-BoldMT" size:17];
firstLockImage = [[UIImageView alloc]init];
secondLockImage = [[UIImageView alloc] init];
[self.contentView addSubview:firstLock];
[self.contentView addSubview:secondLock];
[self.contentView addSubview:firstLockImage];
[self.contentView addSubview:secondLockImage];
}
return self;
}
When one of the UIImageViews is just an image no problem, but it crashes when I add a UIButton (imaged) as a subview.
In the UITableViewDataSource implementation:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UIImage *btnImage = [UIImage imageNamed:#"bike_ok.png"];
UIButton *button =[UIButton alloc];
[button setImage:btnImage forState:UIControlStateNormal];
[cell.secondLockImage addSubview:button];
Adding a button as a subview of the image view crashes:
Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Requesting the window of a view (<UIButton: 0x7bac7d0; frame = (0 0; 0 0); transform = [0, 0, 0, 0, 0, 0]; alpha = 0; opaque = NO; userInteractionEnabled = NO; layer = (null)>) with a nil layer. This view probably hasn't received initWithFrame: or initWithCoder:.'
*** First throw call stack:
What am I missing?
Thanks!
Just add! its important this line
[firstLockImage setUserInteractionEnabled:YES];
[secondLockImage setUserInteractionEnabled:YES];
Because the UIImageView has NO as default and the button doesn't work without it!
If you read the crash error it is quite easy to see where your issue is. You have not initialized your button.
UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(0,0,0,0)];
or you can use initWithCoder.
Hope this helps
Sam
Read the exception text - it says:
This view probably hasn't received initWithFrame: or initWithCoder:
Just a few lines up in your question, you are sending messages to a UIButton instance that you have only alloc'd and not sent any init... message to. That is your error.
Furthermore, you shouldn't directly call the alloc/init pair on UIButton as it's a class cluster and you should usually use +[UIButton buttonWithType:] to get a button instance.
EDIT I'm not 100% sure about that, actually. But you don't really know exactly what you'll get if you do initWithFrame: so I'd still go with buttonWithType: to get a custom button, which is what you want. END EDIT
So, change that line to:
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
Hope this helps!
change UIButton *button =[UIButton alloc]; (alloc w/o init?) to
UIButton *button =[UIButton buttonWithType:UIButtonTypeCustom];
//set frame
[button setFrame:(CGRect){x,y,w,h}];
+buttonWithType handles the alloc/init for your UIButton object

Adding list to a view without changing views

How can I add a list (TableView) to a view without changing views, I want to show the list over the current view but in the middle of the view, so the original view will be showed also.
I tried with label...but gettign some problems adding tableView instead of label.
UIView *testView = [[[UIView alloc] initWithFrame:CGRectMake(0,0, 100, 100)autorelease];
testView.backgroundColor = [[UIColor grayColor] colorWithAlphaComponent:0.2f]; UILabel *label = [[[UILabel alloc] init] autorelease];
label.text = #"TEST";
[label sizeToFit];
[testView addSubview:label];
[self addSubview:testView ];
Refer mjpopupviewcontroller link as it is according to your requirement

UITextField Not Allowing Input

I am programatically adding a UITextField into a UIImageView. When I set the text property, I can see the text.
The issue is, it's not letting me input text into it like an input field when I run the app.
This is my code for initializing the TextField:
UITextField *textField = [[UITextField alloc] init];
textField.frame = CGRectMake(38.0f, 0.0f, self.view.frame.size.width - 38.0f, 40.0f);
textField.text = #"Hello";
textField.background = [[UIImage imageNamed: #"field.png"] stretchableImageWithLeftCapWidth:12 topCapHeight:19];
textField.backgroundColor = [UIColor whiteColor];
textField.userInteractionEnabled = YES;
[bar addSubview: textField];
Do I need to do something special to allow for text input?
If bar is an UIImageView, try to set
bar.userInteractionEnabled = TRUE;
Text Field not added into imageview . You can add textfield on view,for user interaction enabled.
First you can add imageview and then add text field on the view.
Like This--
[self.view addSubview:imgV];
[self.view addSubview: textField];

How to remove a subview which is a UILabel

I have a scroll view, in which I am adding multiple UIImageview's.
For each image view I am adding a UIButton and a UILabel.
Now i want to remove UILabel view.
Please find with my code below
- (void)viewDidLoad {
[super viewDidLoad];
int h;
for (h=0; h<3; h++) {
UIImageView *k=[[UIImageView alloc]initWithFrame:CGRectMake(h*40, 0, 60, 90)];
k.backgroundColor=[UIColor yellowColor];
k.tag=h;
UIButton *j=[[UIButton alloc]initWithFrame:CGRectMake(20, 20, 20, 20)];
[j addTarget:self action:#selector(ge:) forControlEvents: UIControlEventTouchUpInside];
j.backgroundColor=[UIColor redColor];
[k addSubview:j];
k.userInteractionEnabled=YES;
[self.view addSubview:k];
}
}
Here I am just adding an image view and a button. If label exists remove UILabel else add UILabel
Once user click on the button
-(IBAction)ge:(id)sender{
UIImageView *imageView = (UIImageView *)[sender superview];
for (UIView *jkl in [[sender superview]subviews]) {
if ([jkl isKindOfClass:[UILabel class]]){
[jkl removeFromSuperview];
} else {
UILabel *y=[[UILabel alloc]initWithFrame:CGRectMake(20, 20, 20, 20)];
y.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:#"Close.jpeg"]];
[imageView addSubview:y];
}
}
}
but UILabel is not getting removed. Can you please help.
It looks like you're adding the label as a subview of your imageView, but the code that's trying to remove the label is looping through [[sender superview] subviews] – which are the subviews of the imageView's parent view. Try changing that code to loop through [sender subviews] instead.
You are also leaking those UIImageView and UIButton objects. You alloc/init them which sets the retain count to 1, then add them as a subview which sets retain count to 2. When the parent view containing them is released, it releases those views down to a retain count of 1, but never deletes them. You should either do an alloc/init/autorelease on them when you first create them, or release them after you add them as subviews to solve this problem.