How to remove a subview which is a UILabel - objective-c

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.

Related

Xcode 6 Rounded Rect Button Issue

An attempt to programmatically create a rounded rectangular button in an Objective-C View Controller in Xcode 6 and iOS 8.1 only produces a non-rounded rect button. The UIButton buttonWithType: method is being used.
Why?
//
// ViewController.m
//
#import "ViewController.h"
#interface ViewController ()
#end
#implementation ViewController
- (void)loadView // Called the first time the view property is accessed.
{
CGRect viewRect = [[UIScreen mainScreen] bounds];
UIView *view = [[UIView alloc] initWithFrame:viewRect];
self.view = view;
}
- (void)viewDidLoad
{
[super viewDidLoad];
// Set the view's background color.
self.view.backgroundColor = [UIColor colorWithRed:0.462 green:0.999 blue:0.999 alpha:1.0];
// Create a button.
UIButton *btn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
// Place and size the button on the screen.
btn.frame = CGRectMake(100, 100, 90, 44);
// Set the button's background color.
btn.backgroundColor = [UIColor yellowColor];
// Set the button's normal title.
[btn setTitle:#"Test Button" forState:UIControlStateNormal];
// Add the button as a subview.
[self.view addSubview:btn];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#end
Add this line and try:
btn.layer.cornerRadius = 5;

How to get a certain subview from UIView by tag

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];

Adding UIPangesture for UIButton within UIScrollview to move over the all view

In my project i am having scroll at bottom and table at top.
Inside scrollview i am adding 10 buttons.for each button i had pan gesture to move around the screen.when the button intersect with table is will add a picture in tableview.
But the pan is working within the scroll.how to make it move over view
MY coding is:
downscroll=[[UIScrollView alloc]initWithFrame:CGRectMake(24, 635, 980, 100)];
downscroll.backgroundColor=[UIColor redColor];
downscroll.contentSize=CGSizeMake(990, 100);
[self.view addSubview:downscroll];
for(int i=1;i<=8;i++)
{
b1=[UIButton buttonWithType:UIButtonTypeCustom];
b1.frame=CGRectMake(30+px, 0, 80, 80);
[b1 setImage:[UIImage imageNamed: [NSString stringWithFormat:#"Icon%i.png",i]] forState:UIControlStateNormal];
[downscroll addSubview:b1];
// [self.view sendSubviewToBack:b1];
// [self.view bringSubviewToFront:b1];
[groupbutton addObject:b1];
panRecognizer3= [[UIPanGestureRecognizer alloc]initWithTarget:self action:#selector(move:)];
[b1 setUserInteractionEnabled:YES];
b1.exclusiveTouch=YES;
img.tag=i;
[b1 addGestureRecognizer:panRecognizer3];
px=px+120;
}
When i add my buttons directly without scroll scrollview it works fine.But i need to add button scrollview
please help with proper code. Thanks in advance.
Here is the way I used in my application
In my code I follow the below steps
In UIPanGestureRecognizer starting point I add the button to the self.view from scrollView
Drag button by using the translationInView method
3.In UIPanGestureRecognizer end state I'll check if the button dropped in the destination View.If so do your required task else add the button at the same position in the scrollView
`MoveControl` is a UIPanGestureRecognizer method
- (void)MoveControl:(UIPanGestureRecognizer *)recognizer
{
UIButton *vew=(UIButton *)[recognizer view];
CGPoint newCenter = [recognizer translationInView:self.view];
if (recognizer.state==UIGestureRecognizerStateBegan) {
CGPoint point=vew.frame.origin;
[vew setTitle:NSStringFromCGPoint(point) forState:UIControlStateSelected];
CGRect rect=[self.view convertRect:[vew frame] fromView:[vew superview]];
[vew setFrame:rect];
[self.view addSubview:vew];
CGPoint point1=vew.frame.origin;
[vew setTitle:NSStringFromCGPoint(point1) forState:UIControlStateDisabled];
}
else
{
CGPoint oldcentre= CGPointFromString([vew titleForState:UIControlStateDisabled]);
CGRect rect=vew.frame;
CGPoint origin=rect.origin;
origin.x=(newCenter.x+oldcentre.x);
origin.y=(newCenter.y+oldcentre.y);
rect.origin=origin;
vew.frame=rect;
if (CGRectIntersectsRect(rect, [pageOriginalContainer frame])) {
[YourTable setBackgroundColor:[UIColor lightGrayColor]];//Notifying that the tableView will accept the icon
}
else
{
[YourTable setBackgroundColor:[UIColor clearColor]];
}
}
if (recognizer.state==UIGestureRecognizerStateEnded)
{
CGRect rect=[vew frame];
if (CGRectIntersectsRect(rect, [pageOriginalContainer frame])) {
//your method of adding the Image to table
}
else//else part is means for if user dropped dragging somewhere else other than Table
{
CGPoint point=CGPointFromString([vew titleForState:UIControlStateSelected]);
CGRect frame=vew.frame;
frame.origin=point;
vew.frame=frame;
[pageCopyContainer addSubview:vew];
// [NSFileManager defaultManager]
}
}
}

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

Button not clickable after adding as a subview to a UIView

I have created a class called UICustomButton, which is a subclass of UIView. I added a UIButton to UIView as a subview as shown in my code below:
-(id)initWithButtonType:(NSString *)type
{
self = [super init];
if (self)
{
self.customButton = [self setupButtonWithTitle:type andFrame:frame];
[self addSubview:self.customButton];
self.customButton addTarget:self action:#selector(buttonPressed) forControlEvents:UIControlEventTouchUpInside];
}
return self;
}
The problem I am facing is that although the button appears, they are not clickable. Is there something wrong with the way I am adding the buttons to the UIView?
EDIT: To add on, I am using this custom button class instance to a cell:
UICustomButton *customButton = [[UICustomButton alloc]initWithFrame:someFrame];
[cell.contentView addSubView:customButton];
check the frame of your UICustomButton object, and if self.customButton is out of its superView.
Make sure that the frame of the subview is within the frame of its superview. I encountered the issue twice and both times the frame of the subview was incorrect.
You should check if all properties userInteractionEnabled are on:
Check that property for UITableView where your cells with this view are displayed
Check that property for UITableViewCell where you add this view as subview
Check that property for UICustomButton
Check that property for customButton in -(id)initWithButtonType:(NSString *)type
My button was not working because i had two views in each other. The first view, as you can see, has a width and heigth of 0 pixels. I've made this view the same size as view2 and then my button was clickable.
UIView *view1 = [[UIView alloc] initWithFrame:CGRectMake(325, 346, 0, 0)];
view1.alpha = 0.90;
UIView *view2 = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 450, 150)];
[view2.layer setCornerRadius:10.0f];
view2.backgroundColor = [UIColor whiteColor];
UIButton *btn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[btn addTarget:self action:#selector(addClosedToCollection) forControlEvents:UIControlEventTouchUpInside];
[btn setFrame:CGRectMake(30, 30, 300, 32)];
[btn setTitle:#"i'm a button" forState:UIControlStateNormal];
[view2 addSubview:btn];
[view1 addSubview:view2];
i hope i've helped somebody out :)
Your outer view probably has a height of 0. Add constraints that makes it the same height as (or higher than) the subviews, or create it with a frame that is large enough.
try putting this after the if statement:
self.isTouchEnabled = YES;