NSButton NSTrackingArea - tracking doesn't work - objective-c

I'm trying to complete button highlighted on mouse over event. So I subclassed NSButton, where is put NSTrackingArea and methods - (void)mouseEntered:(NSEvent *)event and
- (void)updateTrackingAreas.
Creation of the button looks so (it's in loop so I use array to collect):
CalendarTile *button = [[CalendarTile alloc] init];
[button setFrame:CGRectMake(point_x, point_y, button_frame_width, button_frame_height)];
[button setBordered:NO];
[button setBezelStyle:NSRegularSquareBezelStyle];
[button setButtonType:NSMomentaryChangeButton];
[button setFont:[NSFont fontWithName:#"Avenir Next" size:40]];
[button setAlignment:NSCenterTextAlignment];
[button setTitle:[NSString stringWithFormat:#"%i", i]];
[button setTextColor:[NSColor colorWithCalibratedRed:(float)62/255 green:(float)62/255 blue:(float)62/255 alpha:1.0]];
[arrayWithButtons addObject:button];
...
for (CalendarTile *btn in arrayWithButton) {
[self addSubview:btn];
}
And this is a subclass - CalendarTile.m:
#implementation CalendarTile
- (void)updateTrackingAreas
{
[super updateTrackingAreas];
if (trackingArea)
{
[self removeTrackingArea:trackingArea];
}
NSTrackingAreaOptions options = NSTrackingInVisibleRect | NSTrackingMouseEnteredAndExited | NSTrackingActiveInKeyWindow;
trackingArea = [[NSTrackingArea alloc] initWithRect:NSZeroRect options:options owner:self userInfo:nil];
[self addTrackingArea:trackingArea];
}
- (void)mouseEntered:(NSEvent *)event
{
[self setImage:[NSImage imageNamed:#"highlight.png"]];
NSLog(#"HIGHLIGHT");
}
It should say in logs "HIGHLIGHT" when I have mouse over - it sadly doesn't.
Could you help me? What do I wrong?

Here is i have created and worked for me perfectly...
Step 1: Create the Button with tracking area
NSButton *myButton = [[NSButton alloc] initWithFrame:NSMakeRect(100, 7, 100, 50)];
[myButton setTitle:#"sample"];
[self.window.contentView addSubview:myButton];
// Insert code here to initialize your application
NSTrackingArea* trackingArea = [[NSTrackingArea alloc]
initWithRect:[myButton bounds]
options:NSTrackingMouseEnteredAndExited | NSTrackingActiveAlways
owner:self userInfo:nil];
[myButton addTrackingArea:trackingArea];
Step: 2 Implement the following methods
- (void)mouseEntered:(NSEvent *)theEvent{
NSLog(#"entered");
[[myButton cell] setBackgroundColor:[NSColor blueColor]];
}
- (void)mouseExited:(NSEvent *)theEvent{
[[myButton cell] setBackgroundColor:[NSColor redColor]];
NSLog(#"exited");
}

Try
trackingArea = [[NSTrackingArea alloc] initWithRect:NSZeroRect options:options owner:self userInfo:nil];
instead of
NSTrackingAreaOptions options = NSTrackingMouseEnteredAndExited | NSTrackingActiveAlways;
trackingArea = [[NSTrackingArea alloc] initWithRect:self.frame options:options owner:self userInfo:nil];

Related

remove objects from array based on the index

I have array of images here i am doing check and uncheck the images finally i have delete button which are the images i check i need to remove the images from array based on the button selection
here is my code
- (IBAction)delete_btn_touch:(id)sender {
[MBProgressHUD showHUDAddedTo:self.view animated:YES];
for(int i=0; i<_GalleryimageArry.count;i++){
_imageV = [[UIImageView alloc]initWithFrame:CGRectMake(CGRectGetWidth(self.view.frame) * i/2*0.6, 0, 100, 100)];
self.Crossbtn =[[UIButton alloc]initWithFrame:CGRectMake(_imageV.image.size.width/2+80,0,20,20)];
UIImage *btnImage = [UIImage imageNamed:#"unselectimag"];
[self.Crossbtn setImage:btnImage forState:UIControlStateNormal];
_imageV.contentMode = UIViewContentModeScaleAspectFill;
_imageV.image = [_GalleryimageArry objectAtIndex:i];
[_imageV setUserInteractionEnabled:YES];
_imageV.tag = i;
self.Crossbtn.tag =i;
[self.Crossbtn addTarget:self action:#selector(deleteImage:) forControlEvents:UIControlEventTouchUpInside];
UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:#selector(imageTapMethod:)];
[_imageV addGestureRecognizer:tap];
[self.imageV addSubview:self.Crossbtn];
[self.imageGalleryscroll addSubview:_imageV];
[MBProgressHUD hideAllHUDsForView:self.view animated:YES];
}
self.imageGalleryscroll.delegate = self;
index=0;
self.imageGalleryscroll.contentSize = CGSizeMake(CGRectGetWidth(self.view.frame) * _GalleryimageArry.count/2*0.7, CGRectGetHeight(self.imageGalleryscroll.frame));
[self.imageGalleryscroll setPagingEnabled:YES];
[self.imageGalleryscroll setShowsHorizontalScrollIndicator:NO];
self.imageGalleryscroll.alwaysBounceVertical = NO;
[MBProgressHUD hideHUDForView:self.view animated:YES];
}
-(void)deleteImage:(UIButton *)sender{
btn = (UIButton *)sender;
self.add_delete_view.hidden =YES;
self.deleteview.hidden=NO;
if( [[btn imageForState:UIControlStateNormal] isEqual:[UIImage imageNamed:#"unselectimag"]])
{
[btn setImage:[UIImage imageNamed:#"Crossimg"] forState:UIControlStateNormal];
[btn setSelected:YES];
[btn setTag:index];
}
else
{
[btn setImage:[UIImage imageNamed:#"unselectimag"] forState:UIControlStateNormal];
// other statements
self.selectedimages =#"No";
image = [self.GalleryimageArry objectAtIndex:index];
[self.GalleryimageArry addObject:image];
}
NSLog(#"%#", self.GalleryimageArry);
}
- (IBAction)delete_all_img_btn_touch:(id)sender {
// self.view (change it with your button superview)
if (btn.selected) {
[self.GalleryimageArry removeObjectAtIndex:index];
}
//here i need to removeObjectAtIndex:index based on the how many button are selected
}
any one help me to solve this issues
thanks in advance
Use the following code, where you want to clear the back stack of controllers.
-(void)clearStack
{
NSMutableArray *navigationArray = [[NSMutableArray alloc] initWithArray: self.navigationController.viewControllers];
[navigationArray removeAllObjects];
//[navigationArray removeObjectAtIndex: 2];
self.navigationController.viewControllers = navigationArray;
}

Cannot remove dynamic UIButton

The UIButton is created under #implementation . I have to remove it after some functions but[button removeFromSuperview] doesn't work. How can I remove that?
#import "TabBar.h"
#import "CustomCell.h"
#interface TabBar ()
#end
#implementation TabBar
UILabel *title;
NSString *par;
UIButton *button;
NSMutableArray *backlist;
- (NSString *)documentsDirectory {
return [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
NSUserDomainMask, YES) lastObject];
}
-(void)tbl_info{
NSString *path = [[self documentsDirectory] stringByAppendingPathComponent:#"icd10.plist"];
self.dataList = [[NSMutableArray alloc] initWithContentsOfFile:path];
for (NSInteger i=[self.dataList count]-1; i>=0;i--) {
NSDictionary *d = [self.dataList objectAtIndex:i];
par=[d objectForKey:#"PARENTID"];
if(![par isEqualToString:self.val])
[self.dataList removeObjectAtIndex:i];
}
}
- (IBAction)ara:(id)sender{
[self tbl_info];
[self.tViewTab reloadData];
}
- (NSInteger)tableView:(UITableView *)tableView
numberOfRowsInSection:(NSInteger)section
{
return [self.dataList count];
}
- (CGFloat)tableView:(UITableView *)tableView
heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSString *name= [[self.dataList objectAtIndex:indexPath.row] objectForKey:#"NAME"];
CGSize maxSize = CGSizeMake(320/2, MAXFLOAT);
CGSize labelSize = [name sizeWithFont:[UIFont systemFontOfSize:14] constrainedToSize:maxSize lineBreakMode:NSLineBreakByWordWrapping];
if(labelSize.height>=63)
labelSize.height=63;
return labelSize.height+1;
}
- (UITableViewCell*)tableView:(UITableView *)tableView
cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *cellID = #"cellid";
CustomCell *cell = (CustomCell*)[tableView dequeueReusableCellWithIdentifier:cellID];
if (cell == nil)
{
cell = (CustomCell*)[[[NSBundle mainBundle]
loadNibNamed:#"CustomCell" owner:nil options:nil]
lastObject];
}
NSDictionary *d = [self.dataList objectAtIndex:indexPath.row];
cell.nameLabel.text = [d objectForKey:#"NAME"];
cell.cityLabel.text = [d objectForKey:#"CODE"];
cell.indexPath = indexPath;
CGSize maxSize = CGSizeMake(320/2, MAXFLOAT);
CGSize nameSize = [cell.nameLabel.text sizeWithFont:[UIFont systemFontOfSize:14] constrainedToSize:maxSize lineBreakMode:NSLineBreakByWordWrapping];
if(nameSize.height>=63)
nameSize.height=63;
cell.nameLabel.frame =CGRectMake(80, 0, 234, nameSize.height);
cell.cityLabel.text = [d objectForKey:#"CODE"];
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
NSDictionary *d = [self.dataList objectAtIndex:indexPath.row];
NSMutableDictionary *backprop = [[NSMutableDictionary alloc] init];
[backprop setObject:self.val forKey:#"id"];
[backprop setObject:title.text forKey:#"name"];
[backlist addObject:backprop];
//back button
button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[button addTarget:self action:#selector(touchEvent:) forControlEvents:UIControlEventTouchUpInside];
[button setTitle:title.text forState:UIControlStateNormal];
button.frame = CGRectMake(02.0, 02.0, 71, 32);
[self.view addSubview:button];
//parent and title label
[title setText:[d objectForKey:#"NAME"]];
self.val=[d objectForKey:#"ID"];
[self tbl_info];
[self.tViewTab reloadData];
}
-(void)touchEvent:(id)sender{
[title setText:[[backlist objectAtIndex:backlist.count-1] objectForKey:#"name" ]];
self.val= [[backlist objectAtIndex:backlist.count-1] objectForKey:#"id"];
[backlist removeObjectAtIndex:backlist.count-1];
if(backlist.count>0)
[button setTitle:[[backlist objectAtIndex:backlist.count-1] objectForKey:#"name" ] forState:UIControlStateNormal];
else
[button removeFromSuperview];
[self tbl_info];
[self.tViewTab reloadData];
}
- (void)viewDidLoad
{
[super viewDidLoad];
backlist =[[NSMutableArray alloc]init];
self.val=#"0";
[self tbl_info];
[self.tViewTab reloadData];
title =[[UILabel alloc]initWithFrame:CGRectMake(79.0, 07.0, 162, 21)];
title.text = #"ICD10 Kod Grupları"; //etc...
[self.view addSubview:title];
[title release];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
}
In place of this :
button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[button addTarget:self action:#selector(touchEvent:) forControlEvents:UIControlEventTouchUpInside];
[button setTitle:title.text forState:UIControlStateNormal];
button.frame = CGRectMake(02.0, 02.0, 71, 32);
[self.view addSubview:button];
Try this :
if (button != nil) {
button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[button addTarget:self action:#selector(touchEvent:) forControlEvents:UIControlEventTouchUpInside];
[button setTitle:title.text forState:UIControlStateNormal];
button.frame = CGRectMake(02.0, 02.0, 71, 32);
[self.view addSubview:button];
}
Or try this :
if (button != nil) {
[button removeFromSuperView];
[button release]; // dont write this in case of ARC
button = nil;
}
button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[button addTarget:self action:#selector(touchEvent:) forControlEvents:UIControlEventTouchUpInside];
[button setTitle:title.text forState:UIControlStateNormal];
button.frame = CGRectMake(02.0, 02.0, 71, 32);
[self.view addSubview:button];
Not a solution but a workaround:
Use
[sender removeFromSuperview];
or respectively, because sender is of type id and not UIView*:
[(UIButton*)sender removeFromSuperview];
But you could change sender to UIView* savely.
-(void)touchEvent:(UIView *)sender{
Some even put UIButton* in there. I personally don't like that but it is quite save if you know for sure that the message is sent by UIButtons only.
Another workaround would be to set the .tag property of the button and then fetch the real buttom from self.view by its tag.

UIButton as a subview in MKAnnotationView doesn't work

I have added a button to my annotation view, and it appears correctly. When the button is tapped, I want a call to be made, but when I tap the button, it doesn't respond (the button doesn't even highlight). It seems that the button doesn't receive the touch event, but I don't know why.
Here is my code in customAnnotationView.m
- (id)initWithAnnotation:(id <MKAnnotation>)annotation reuseIdentifier:(NSString *)reuseIdentifier
{
NSLog(#"initWithAnnotation start");
//initialze the view
self = [super initWithAnnotation:annotation reuseIdentifier:reuseIdentifier];
if (self != nil)
{
CGRect frame = self.frame;
frame.size = CGSizeMake(60.0, 85.0);
self.frame = frame;
self.backgroundColor = [UIColor clearColor];
self.centerOffset = CGPointMake(30.0, 42.0);
}
//this has nothing to do with my question
self.title=[[[NSString alloc] init] autorelease];
self.description=[[[NSString alloc] init] autorelease];
self.phoneNumber=[[[NSString alloc] init] autorelease];
customAnnotation * tempCust = (customAnnotation *)annotation;
self.title=annotation.title;
self.description=tempCust.description;
self.phoneNumber=tempCust.phoneNumber;
//here is the question button
self.userInteractionEnabled=YES;
self.exclusiveTouch=NO;
UIButton *button=[UIButton buttonWithType:UIButtonTypeRoundedRect];
[button setTitle:#"Call" forState:UIControlStateNormal];
//decide the button's position
CGRect rect=button.frame;
rect.origin.x=15;
rect.origin.y=47;
rect.size.width=40;
rect.size.height=20;
button.frame=rect;
[self addSubview:button];
[button becomeFirstResponder];
[button addTarget:self action:#selector(buttonClicked:) forControlEvents:UIControlEventTouchUpInside];
NSLog(#"initWithAnnotation finished");
return self;
}
//action method
-(void)buttonClicked:(id)sender{
NSString *callNumber=[[[NSString alloc] initWithFormat:#"tel://%#",self.phoneNumber] autorelease];
[[UIApplication sharedApplication]openURL:[NSURL URLWithString:callNumber]];
}
Why doesn't the button work?
self.rightCalloutAccessoryView = button;
Use the above instead of [self addSubview:button];
Hope this help's you

is it Possible to pass parameter in UIView Class

I ve got a view controller . when i pass an extra object I m getting this error #No visible interface in the below function .could u help me out.below is the code.where i am passing an object of type photo ..
ItemImageView *itemImage = [[ItemImageView alloc]initWithFrame:CGRectMake(currentPhotoPositionX,0,pageButtonWidth,pageButtonHeight) andPhoto:photo];
#ItemImageview
- (id)initWithFrame:(CGRect)frame :andPhoto:(Photo *)photo
{
self = [super initWithFrame:frame];
if (self) {
// Initialization code
//Create Activity Indicator
activityIndicator= [[UIActivityIndicatorView alloc]initWithFrame:CGRectMake(225, 115, 30, 30)];
[activityIndicator setBackgroundColor:[UIColor clearColor]];
[activityIndicator setActivityIndicatorViewStyle:UIActivityIndicatorViewStyleWhite];
[self addSubview:activityIndicator];
//Create Label Comments
lblComments = [[UILabel alloc] initWithFrame:CGRectMake(30.0f, 100.0f, 60.0f, 43.0f)];
[lblComments setText:#"Comments"];
[lblComments setBackgroundColor:[UIColor clearColor]];
[self addSubview:lblComments];
//Create Label Likes
lblLikes = [[UILabel alloc] initWithFrame:CGRectMake(100.0f, 100.0f, 60.0f, 43.0f)];
[lblLikes setText:#"Likes"];
[lblLikes setBackgroundColor:[UIColor clearColor]];
[self addSubview:lblLikes];
//Create Item Button
btnItem = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[btnItem addTarget:self
action:#selector(:)
forControlEvents:UIControlEventTouchUpInside];
[btnItem setBackgroundImage:[UIImage imageNamed:#"1.png"] forState:UIControlStateNormal];
btnItem.frame = CGRectMake(0.0f, 0.0f, 144.0f, 143.0f);
[self addSubview:btnItem];
}
return self;
}
Change it into:
- (id)initWithFrame:(CGRect)frame andPhoto:(Photo *)photo
And also remember to add it to your .h file.

How to add clickable Links to UILabel with attributedText in iOS 6

I used DTCoreText to display formatted text in my apps. DTAttributedTextView also supports clickable links.
Since iOS6 we can use the setAttributedText function to display attributedStrings in UILabel.
But how can I display Links that are clickable? Is there a way to call a delegate Function etc. when a link is pressed?
The iOS 6.0 UILabel still cant display clickable links.
However you could use a UITextView instead. The textview can detect links, but the link detection only work if editing of text is disabled. Limitations are that you cant do something like this in BBCode [url=www.apple.com]Apples Website[/url].
Here is example code to hyperlink UILabel:
Source:http://sickprogrammersarea.blogspot.in/2014/03/adding-links-to-uilabel.html
#import "ViewController.h"
#import "TTTAttributedLabel.h"
#interface ViewController ()
#end
#implementation ViewController
{
UITextField *loc;
TTTAttributedLabel *data;
}
- (void)viewDidLoad
{
[super viewDidLoad];
UILabel *lbl = [[UILabel alloc] initWithFrame:CGRectMake(5, 20, 80, 25) ];
[lbl setText:#"Text:"];
[lbl setFont:[UIFont fontWithName:#"Verdana" size:16]];
[lbl setTextColor:[UIColor grayColor]];
loc=[[UITextField alloc] initWithFrame:CGRectMake(4, 20, 300, 30)];
//loc.backgroundColor = [UIColor grayColor];
loc.borderStyle=UITextBorderStyleRoundedRect;
loc.clearButtonMode=UITextFieldViewModeWhileEditing;
//[loc setText:#"Enter Location"];
loc.clearsOnInsertion = YES;
loc.leftView=lbl;
loc.leftViewMode=UITextFieldViewModeAlways;
[loc setDelegate:self];
[self.view addSubview:loc];
[loc setRightViewMode:UITextFieldViewModeAlways];
CGRect frameimg = CGRectMake(110, 70, 70,30);
UIButton *srchButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
srchButton.frame=frameimg;
[srchButton setTitle:#"Go" forState:UIControlStateNormal];
[srchButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
srchButton.backgroundColor=[UIColor clearColor];
[srchButton addTarget:self action:#selector(go:) forControlEvents:UIControlEventTouchDown];
[self.view addSubview:srchButton];
data = [[TTTAttributedLabel alloc] initWithFrame:CGRectMake(5, 120,self.view.frame.size.width,200) ];
[data setFont:[UIFont fontWithName:#"Verdana" size:16]];
[data setTextColor:[UIColor blackColor]];
data.numberOfLines=0;
data.delegate = self;
data.enabledTextCheckingTypes=NSTextCheckingTypeLink|NSTextCheckingTypePhoneNumber;
[self.view addSubview:data];
}
- (void)attributedLabel:(TTTAttributedLabel *)label didSelectLinkWithURL:(NSURL *)url
{
NSString *val=[[NSString alloc]initWithFormat:#"%#",url];
if ([[url scheme] hasPrefix:#"mailto"]) {
NSLog(#" mail URL Selected : %#",url);
MFMailComposeViewController *comp=[[MFMailComposeViewController alloc]init];
[comp setMailComposeDelegate:self];
if([MFMailComposeViewController canSendMail])
{
NSString *recp=[[val substringToIndex:[val length]] substringFromIndex:7];
NSLog(#"Recept : %#",recp);
[comp setToRecipients:[NSArray arrayWithObjects:recp, nil]];
[comp setSubject:#"From my app"];
[comp setMessageBody:#"Hello bro" isHTML:NO];
[comp setModalTransitionStyle:UIModalTransitionStyleCrossDissolve];
[self presentViewController:comp animated:YES completion:nil];
}
}
else{
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:val]];
}
}
-(void)mailComposeController:(MFMailComposeViewController *)controller didFinishWithResult:(MFMailComposeResult)result error:(NSError *)error{
if(error)
{
UIAlertView *alrt=[[UIAlertView alloc]initWithTitle:#"Erorr" message:#"Some error occureed" delegate:nil cancelButtonTitle:#"" otherButtonTitles:nil, nil];
[alrt show];
[self dismissViewControllerAnimated:YES completion:nil];
}
else{
[self dismissViewControllerAnimated:YES completion:nil];
}
}
- (void)attributedLabel:(TTTAttributedLabel *)label didSelectLinkWithPhoneNumber:(NSString *)phoneNumber
{
NSLog(#"Phone Number Selected : %#",phoneNumber);
UIDevice *device = [UIDevice currentDevice];
if ([[device model] isEqualToString:#"iPhone"] ) {
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:[NSString stringWithFormat:#"tel:%#",phoneNumber]]];
} else {
UIAlertView *Notpermitted=[[UIAlertView alloc] initWithTitle:#"Alert" message:#"Your device doesn't support this feature." delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
[Notpermitted show];
}
}
-(void)go:(id)sender
{
[data setText:loc.text];
}
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
NSLog(#"Reached");
[loc resignFirstResponder];
}