I create a custom alertview that subview a uitextview inside it, as shown in the screenshot.
alertview with subviewed textview
I want to disable the Submit button when the textview is empty, so I edited the alertViewShouldEnableFirstOtherButton method:
- (BOOL)alertViewShouldEnableFirstOtherButton:(UIAlertView *)alertView
{
if ( alertView.tag == 5000 ) {
for(UIView *view in alertView.subviews) {
if([view isKindOfClass:[UITextView class]]) {
UITextView *textField = (UITextView *)view;
if ( textField.text.length == 0 ) {
return NO ;
}
return YES ;
}
}
}
else {
return YES ;
}
}
Initially, the Submit button is disable which is right, but after I edit (type something on the textview), the submit button is still disabled, it seems that the alertViewShouldEnableFirstOtherButton only call once.
So, can someone teach me how to enable the submit button after I type in something on the subviewed textview? Thanks for the great help.
##########First edit
Below is the full code about the alertview,
- (void)addRemarkAlert {
alert = [[UIAlertView alloc]
initWithTitle:[NSString stringWithFormat:#"Remarks\n\n\n\n\n\n"]
message:nil
delegate:self
cancelButtonTitle: #"Cancel"
otherButtonTitles:#"Submit", nil ];
// textView to subview in the alertview
textView_onAlertView = [[UITextView alloc]initWithFrame:CGRectMake(12, 50, 260, 100)];
textView_onAlertView.delegate = self ;
textView_onAlertView.layer.borderWidth = 2.0f;
textView_onAlertView.layer.borderColor = [[UIColor darkGrayColor] CGColor];
textView_onAlertView.layer.cornerRadius = 10.0f;
textView_onAlertView.clipsToBounds = YES ;
textView_onAlertView.autocorrectionType = UITextAutocorrectionTypeNo ;
textView_onAlertView.autocapitalizationType = UITextAutocapitalizationTypeSentences ;
textView_onAlertView.font = [UIFont fontWithName:#"HelveticaNeue-Bold" size:12];
[alert addSubview:textView_onAlertView];
alert.tag = 5000 ;
[alert show];
}
- (BOOL)alertViewShouldEnableFirstOtherButton:(UIAlertView *)alertView
{
if ( alertView.tag == 5000 ) {
for(UIView *view in alertView.subviews)
{
if([view isKindOfClass:[UIButton class]])
{
UIButton *aButton = (UIButton *)view;
if([aButton.titleLabel.text isEqualToString:#"Submit"])
{
if ( textView_onAlertView.text.length> 0 )
{
((UIButton *) view).enabled = YES;
}
else
{
((UIButton *) view).enabled = NO;
}
}
}
}
return NO;
}
else {
return YES ;
}
}
- (BOOL)alertViewShouldEnableFirstOtherButton:(UIAlertView *)alertView
{
NSLog(#"%d",tv.text.length);
for(UIView *view in alertView.subviews)
{
if([view isKindOfClass:[UIButton class]])
{
UIButton *aButton = (UIButton *)view;
if([aButton.titleLabel.text isEqualToString:#"done"])
{
if ( tv.text.length> 0 )
{
((UIButton *) view).enabled = YES;
}
else
{
((UIButton *) view).enabled = NO;
}
}
}
}
return NO;
}
//////////////////////////////////////Entire code for your question
- (void)viewDidLoad
{
[super viewDidLoad];
[self addRemarkAlert];
}
- (void)addRemarkAlert
{
alert = [[UIAlertView alloc]
initWithTitle:[NSString stringWithFormat:#"Remarks\n\n\n\n\n\n"]
message:nil
delegate:self
cancelButtonTitle: #"Cancel"
otherButtonTitles:#"Submit", nil ];
// textView to subview in the alertview
textView_onAlertView = [[UITextView alloc]initWithFrame:CGRectMake(12, 50, 260, 100)];
textView_onAlertView.delegate = self ;
textView_onAlertView.layer.borderWidth = 2.0f;
textView_onAlertView.layer.borderColor = [[UIColor darkGrayColor] CGColor];
textView_onAlertView.layer.cornerRadius = 10.0f;
textView_onAlertView.clipsToBounds = YES ;
textView_onAlertView.autocorrectionType = UITextAutocorrectionTypeNo ;
textView_onAlertView.autocapitalizationType = UITextAutocapitalizationTypeSentences ;
textView_onAlertView.font = [UIFont fontWithName:#"HelveticaNeue-Bold" size:12];
[alert addSubview:textView_onAlertView];
alert.tag = 5000 ;
[alert show];
}
- (BOOL)alertViewShouldEnableFirstOtherButton:(UIAlertView *)alertView
{
if ( alertView.tag == 5000 ) {
for(UIView *view in alertView.subviews)
{
if([view isKindOfClass:[UIButton class]])
{
UIButton *aButton = (UIButton *)view;
if([aButton.titleLabel.text isEqualToString:#"Submit"])
{
if ( textView_onAlertView.text.length> 0 )
{
((UIButton *) view).enabled = YES;
}
else
{
((UIButton *) view).enabled = NO;
}
}
}
}
return NO;
}
else
{
return YES ;
}
}
- (void)textViewDidChange:(UITextView *)textView
{
[self alertViewShouldEnableFirstOtherButton:alert];
}
Related
I am trying to turn off a UIPanGestureRecognizer with the click of a "Save" button. Then, I am trying to turn back on this UIPanGestureRecognizer with the click of an "Edit" button. I can figure out how to turn them off with the following code like this:
- (IBAction)saveButton:(id)sender {
buttonCount ++;
if (buttonCount > 0) {
for (_buttonField in self.view.subviews) {
_buttonField.gestureRecognizers = nil;
_buttonField.layer.borderColor = [UIColor blackColor].CGColor;
}
}
}
Yet, I have two problems. First of all, this is turning off all of the gesture recognizers, which I do not want to do. Secondly, I cannot figure out how to turn them back on. For this I have tried the following:
- (IBAction)editButton:(id)sender {
buttonCount ++;
if (buttonCount > 0) {
if ([[UIColor colorWithCGColor:_buttonField.layer.borderColor] isEqual:[UIColor whiteColor]]) {
for (_buttonField in self.view.subviews) {
_buttonField.gestureRecognizers = YES;
}
}
}
}
However, I receive an error on the line of code that is set to YES.
Here is my complete set of code for reference:
#implementation FieldGoalChartViewController
{
}
-(void)viewDidLoad{
[super viewDidLoad];
}
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(nullable UIEvent *)event {
UITouch *aTouch = [touches anyObject];
CGRect buttonRect = self.buttonField.frame;
CGPoint point = [aTouch locationInView:self.buttonField.superview];
if (!CGRectContainsPoint(buttonRect, point)) {
_buttonField.layer.borderColor = [UIColor blackColor].CGColor;
_draggedView.layer.borderColor = [UIColor blackColor].CGColor;
for (_buttonField in self.view.subviews) {
_buttonField.layer.borderColor = [UIColor blackColor].CGColor;
}
}
}
- (void)longPress:(UILongPressGestureRecognizer*)gesture {
if ( gesture.state == UIGestureRecognizerStateBegan ) {
gesture.view.layer.borderColor = [UIColor whiteColor].CGColor;
UIAlertController * alert= [UIAlertController
alertControllerWithTitle:#"Would you like to delete the selected rep(s)?"
message:nil
preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction* deleteButton = [UIAlertAction
actionWithTitle:#"Delete"
style:UIAlertActionStyleDefault
handler:^(UIAlertAction * action)
{
for (_buttonField in self.view.subviews) {
if ([[UIColor colorWithCGColor:_buttonField.layer.borderColor] isEqual:[UIColor whiteColor]]) {
[_buttonField removeFromSuperview];
}
}
[alert dismissViewControllerAnimated:YES completion:nil];
}];
UIAlertAction* cancelButton = [UIAlertAction
actionWithTitle:#"Cancel"
style:UIAlertActionStyleDefault
handler:^(UIAlertAction * action)
{
[alert dismissViewControllerAnimated:YES completion:nil];
}];
[alert addAction:deleteButton];
[alert addAction:cancelButton];
[self presentViewController:alert animated:YES completion:nil];
}
}
- (void)panWasRecognized:(UIPanGestureRecognizer *)panner {
{
panner.view.layer.borderColor = [UIColor whiteColor].CGColor;
_draggedView = panner.view;
CGPoint offset = [panner translationInView:_draggedView.superview];
CGPoint center = _draggedView.center;
_draggedView.center = CGPointMake(center.x + offset.x, center.y + offset.y);
_draggedView.layer.masksToBounds =YES;
_buttonField.layer.borderWidth = 3.0f;
// Reset translation to zero so on the next `panWasRecognized:` message, the
// translation will just be the additional movement of the touch since now.
[panner setTranslation:CGPointZero inView:_draggedView.superview];
}
}
-(void)buttonTouched:(UIButton*)sender forEvent:(id)tap {
NSSet *touches = [tap allTouches];
UITouch *touch = [touches anyObject];
UITouchPhase *phase = touch.phase;
touch.view.layer.borderColor = [UIColor whiteColor
].CGColor;
}
-(void)doubleTapped:(UIButton*)sender forEvent:(id)twoTaps {
NSSet *touches = [twoTaps allTouches];
UITouch *touch = [touches anyObject];
UITouchPhase *phase = touch.phase;
touch.view.layer.borderColor = [UIColor blackColor].CGColor;
}
- (IBAction)saveButton:(id)sender {
buttonCount ++;
if (buttonCount > 0) {
for (_buttonField in self.view.subviews) {
_buttonField.gestureRecognizers = nil;
_buttonField.layer.borderColor = [UIColor blackColor].CGColor;
}
}
}
- (IBAction)editButton:(id)sender {
buttonCount ++;
if (buttonCount > 0) {
if ([[UIColor colorWithCGColor:_buttonField.layer.borderColor] isEqual:[UIColor whiteColor]]) {
for (_buttonField in self.view.subviews) {
_buttonField.gestureRecognizers = YES;
}
}
}
}
- (IBAction)addRepButton:(UIBarButtonItem *)newRep {
self.labelCounter++;
buttonCount ++;
if (buttonCount > 0 )
{
_buttonField = [[UIButton alloc]initWithFrame:CGRectMake(300, 300, 28, 28)];
[_buttonField setTitle:[NSString stringWithFormat:#"%i", self.labelCounter]forState:UIControlStateNormal];
[_buttonField setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
_buttonField.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter;
_buttonField.userInteractionEnabled = YES;
_buttonField.layer.cornerRadius = 14;
_buttonField.layer.borderColor = [UIColor blackColor].CGColor;
_buttonField.layer.borderWidth = 3.0f;
_buttonField.titleLabel.font = [UIFont boldSystemFontOfSize:13];
[_buttonField setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
_buttonField.layer.backgroundColor = [UIColor blackColor].CGColor;
_buttonField.layer.masksToBounds = YES;
//Pan gesture declared in button
UIPanGestureRecognizer *panner = [[UIPanGestureRecognizer alloc] initWithTarget:self action:#selector(panWasRecognized:)];
[_buttonField addGestureRecognizer:panner];
//Long Press gesture declared in button
UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:#selector(longPress:)];
[self.buttonField addGestureRecognizer:longPress];
//Touch down inside declared in button
[self.buttonField addTarget:self action:#selector(buttonTouched:forEvent:) forControlEvents:UIControlEventTouchDown];
//Double Tap inside declared in button
[self.buttonField addTarget:self action:#selector(doubleTapped:forEvent:) forControlEvents:UIControlEventTouchDownRepeat];
[self.view addSubview:(_buttonField)];
}
}
#end
I want to know how to specifically turn off the UIPanGestureRecognizer with the click of my "Save" UIBarButton, and then turn the UIPanGestureRecognizer with the click of my "Edit" UIBarButton.
If you added Pan gesture in IB then you can create outlet and use the enabled property on the instance of the gesture to enable and disable the gesture, simple.
panGestureRecognizer.enabled = NO; (or)
panGestureRecognizer.enabled = YES;
I have a single UIButton in the view of my UIViewController. I also have ten more that are in a subview in the main view. I want to find all these buttons. So far I have:
-(void)findAllButtons{
for(UIView *view in self.view.subviews) {
if ([view isKindOfClass:[myButton class]]){
NSLog(#"found a button!");
}
}
}
It is only finding the single button though and not the other ten. Why is that? Shouldn't it iterate every single subview and then find them?
for (UIView *subView in scroll.subviews) {
if ([subView isKindOfClass:[UIButton class]]) {
UIButton *btn = (UIButton*)subView;
if (btn.tag == selectedButton.tag) {
btn.layer.borderWidth = 1.0f;
btn.layer.borderColor = [UIColor darkGrayColor].CGColor;
}else{
btn.layer.borderWidth = 1.0f;
btn.layer.borderColor = [UIColor clearColor].CGColor;
}
}
}
Just a few lines of code
-(void)findAllButtons {
[self findButtonsInSubviews:self.view.subviews];
}
- (void)findButtonsInSubviews:(NSArray *)subviews {
for(UIView *view in subviews) {
if ([view isKindOfClass:[UIButton class]]){
NSLog(#"found a button!");
} else {
[self findButtonsInSubviews:view.subviews];
}
}
}
A recursive function using Objective-C blocks like this will find all views of a given subclass type as specified in the test block in the view hierarchy of the given view:
NSMutableArray *marrAllButtons = [NSMutableArray new];
BOOL (^viewTest)(UIView*) = ^BOOL(UIView* viewToTest) {
return [view isKindOfClass:[UIButton class]];
};
void(^viewEnumerator)(UIView*) = ^(UIView* outerView){
for (UIView *view in outerView.subviews)
{
if (viewTest(view))
{
[marrAllButtons addObject:view];
}
else
{
viewEnumerator(view);
}
}
};
viewEnumerator(self.view);
NSLog(#"All Buttons %#", marrAllButtons);
- (NSMutableArray *)buttonsInView:(UIView *)view
{
NSArray *subviews = view.subviews;
NSMutableArray *buttons = [NSMutableArray array];
for (UIView *subview in subviews)
{
if ([subview isKindOfClass:[UILabel class]])
{
[buttons addObject:subview];
}
else if(subview.subviews)
{
[buttons addObjectsFromArray:[self buttonsInView:subview]];
}
}
return buttons;
}
Your method is right if all your button already have in self.view (main view).
Just set tag for all button to check and also make sure that all button are on the main view. I hope this will work.
-(void)findAllButtons{
for(UIView *view in self.view.subviews) {
if ([view isKindOfClass:[myButton class]]){
UIButton *button = (UIButton*)view;
NSLog(#"found a button with tag:%d",button.tag);
}
}
}
for(UIView * subView in view.subviews) // here write Name of you ScrollView.
{
// NSLog(#"test %#", [subView class]);
if([subView isKindOfClass:[UIButton class]])
{
UIButton *button = (UIButton*)subView;
[button setSelected:NO] ;
NSString *s1;
s1 = #",";
s1 = [s1 stringByAppendingString:[NSString stringWithFormat:#"%#",button.titleLabel.text ]];
s1 = [s1 stringByAppendingString:[NSString stringWithFormat:#"%#",#"," ]];
NSRange range = [temp_Colors_Name_comma rangeOfString:s1 ];
if(range.location == NSNotFound)
{
}
else
{
[button setSelected:YES];
}
}
}
I've been searching the internet and trying different thing but cannot seem to change the button title colour on my action sheet.
Here is the action sheet code.
- (void)showActionSheet
{
UIActionSheet *actionSheet = [[UIActionSheet alloc]
initWithTitle:#"Select Country"
delegate:self
cancelButtonTitle:nil
destructiveButtonTitle:nil
otherButtonTitles:nil];
for (NSString *listCountry in resultSet) [actionSheet addButtonWithTitle:listCountry];
[actionSheet showInView:[self.view window]];
}
I've tried this delegate but it does not work.
- (void)willPresentActionSheet:(UIActionSheet *)actionSheet
{
for (UIView *subview in actionSheet.subviews) {
if ([subview isKindOfClass:[UIButton class]]) {
UIButton *button = (UIButton *)subview;
button.titleLabel.textColor = [UIColor greenColor];
}
}
}
Make sure you set, UIActionSheet delegate and set breakpoint on this method,
willPresentActionSheet,
check whether this method getting called .
If you have set delegate means, try this one
- (void) changeTextColorForUIActionSheet:(UIActionSheet*)actionSheet {
UIColor *tintColor = [UIColor redColor];
NSArray *actionSheetButtons = actionSheet.subviews;
for (int i = 0; [actionSheetButtons count] > i; i++) {
UIView *view = (UIView*)[actionSheetButtons objectAtIndex:i];
if([view isKindOfClass:[UIButton class]]){
UIButton *btn = (UIButton*)view;
[btn setTitleColor:tintColor forState:UIControlStateNormal];
}
}
}
Update:
https://github.com/seivan/SHActionSheetBlocks
https://github.com/ianb821/IBActionSheet
You must implement UIActionSheetDelegate and then you can use willPresentActionSheet delegate method
- (void)willPresentActionSheet:(UIActionSheet *)actionSheet
{
for (UIView *subview in actionSheet.subviews) {
if ([subview isKindOfClass:[UIButton class]]) {
UIButton *button = (UIButton *)subview;
[button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
}
}
}
I took this project from github.
It is custom AlertView. I understood how it works. Modified it for my project, like this
Course1 - name of some product, and '1' - is its amount. When I'm typing on plus/minus amount increases/decreases. But it works only for my variable (which I load on this AlertView, when I show it, and it is 1). How can I reload message of this alert view with changing var (amount). I can't understand.
Here my code.
In my class I call alert view by this code
BlockAlertView *alert = [BlockAlertView alertWithTitle: title message:ac.acCount];
[alert setCancelButtonWithTitle:#"-" block:nil];
[alert setDestructiveButtonWithTitle:#"+" block:^{
int u = [ac.acCount intValue];
u++;
ac.acCount = [NSString stringWithFormat:#"%d", u];
NSLog(#"%d", u);
}];
[alert addButtonWithTitle:#"Ok" block:^{
NSMutableArray *container = [[NSMutableArray alloc] init];
[container addObject:title];
[container addObject:price];
[container addObject:bId];
[container addObject:ac.acCount];
[container addObject:depid];
[[NSNotificationCenter defaultCenter] postNotificationName:#"MyNotification" object:container];
}];
[alert show];
Show method just draws alert view with params which takes from alertWithTitle: title message:ac.acCount. Here is the code
+ (BlockAlertView *)alertWithTitle:(NSString *)title message:(NSString *)message
{
return [[[BlockAlertView alloc] initWithTitle:title message:message] autorelease];
}
here is
- (id)initWithTitle:(NSString *)title message:(NSString *)message
{
NSLog(#"title - %# message - %#", title, message);
if ((self = [super init]))
{
UIWindow *parentView = [BlockBackground sharedInstance];
CGRect frame = parentView.bounds;
frame.origin.x = floorf((frame.size.width - background.size.width) * 0.5);
frame.size.width = background.size.width;
_view = [[UIView alloc] initWithFrame:frame];
_blocks = [[NSMutableArray alloc] init];
_height = kAlertViewBorder + 6;
if (title)
{
CGSize size = [title sizeWithFont:titleFont
constrainedToSize:CGSizeMake(frame.size.width-kAlertViewBorder*2, 1000)
lineBreakMode:UILineBreakModeWordWrap];
UILabel *labelView = [[UILabel alloc] initWithFrame:CGRectMake(kAlertViewBorder, _height, frame.size.width-kAlertViewBorder*2, size.height)];
labelView.font = titleFont;
labelView.numberOfLines = 0;
labelView.lineBreakMode = UILineBreakModeWordWrap;
labelView.textColor = kAlertViewTitleTextColor;
labelView.backgroundColor = [UIColor clearColor];
labelView.textAlignment = UITextAlignmentCenter;
labelView.shadowColor = kAlertViewTitleShadowColor;
labelView.shadowOffset = kAlertViewTitleShadowOffset;
labelView.text = title;
[_view addSubview:labelView];
[labelView release];
_height += size.height + kAlertViewBorder;
}
if (message)
{
CGSize size = [message sizeWithFont:messageFont
constrainedToSize:CGSizeMake(frame.size.width-kAlertViewBorder*2, 1000)
lineBreakMode:UILineBreakModeWordWrap];
UILabel *labelView = [[UILabel alloc] initWithFrame:CGRectMake(kAlertViewBorder, _height, frame.size.width-kAlertViewBorder*2, size.height)];
labelView.font = messageFont;
labelView.numberOfLines = 0;
labelView.lineBreakMode = UILineBreakModeWordWrap;
labelView.textColor = kAlertViewMessageTextColor;
labelView.backgroundColor = [UIColor clearColor];
labelView.textAlignment = UITextAlignmentCenter;
labelView.shadowColor = kAlertViewMessageShadowColor;
labelView.shadowOffset = kAlertViewMessageShadowOffset;
labelView.text = message;
[_view addSubview:labelView];
[labelView release];
_height += size.height + kAlertViewBorder;
}
_vignetteBackground = NO;
}
return self;
}
I tried to use something like this
-(void)reloadAlertView: (NSString *) title: (NSString *) message{
[self initWithTitle:title message:message];
}
and call this from my class, where i shows alert view.
[alert reloadAlertView: title: newMessage];
YOu need to ref a new label in your CustomAlertView.h
#property (nonatomic, strong) IBOutlet UILabel *mylab;
then you can get the properties of this label by the object of the CustomAlertView.h class
BlockAlertView *alert ...;
alert.mylab.text = #"hello";
solution (simple , not required to hack the BlockAlertView.m)
whenever the + button is click, the alert will be disappeared, and reappeared again.
ViewController.m
#implementation ViewController {
BlockAlertView *alert ;
NSInteger value;
}
-(void) viewDidLoad {
value = 0;
[self reloadAlert];
}
-(void) reloadAlert {
value += 1;
__block ViewController* _self = self;
alert = [[BlockAlertView alloc] initWithTitle:#"Course1" message:[[[NSNumber alloc] initWithInteger:value ] stringValue]];
[alert setDestructiveButtonWithTitle:#"PLUS" block:^{
[_self reloadAlert];
}];
[alert show];
}
}
solution , if you want to keep the AlertView remained, without popping up.
a. Modify BlockAlertView.h to bring messageLabelView outside to be accessed from ViewController, so we can redraw the message later.
BlockAlertView.h
#interface BlockAlertView {
...
}
#property (nonatomic, retain) UILabel *messageLabelView;
You can also bring the UIView *_view out of #protected and into #property instead, if preferred. In that case, messageLabelView can be access via _view 's subviews
b. Modify BlockAlertView.m dismissWithClickedButtonIndex:animated: to disable removeView function from being called if buttonIndex == PLUS sign button - buttonIndex to be hardcoded to 0.
There may be a better option to stop the execution thread inside the block obj of PLUS button, but I dont know how to do :)
c. Modify BlockAlert.m initWithTitle:message: to add reference of messageLabelView into labelView during the render of message Label.
BlockAlertView.m
#synthesize messageLabelView;
- (id)initWithTitle:(NSString *)title message:(NSString *)message
{
...
// code to initialize messageLabelView
if (message)
{
....
// code to render labelView for message. add reference to messageLabelView
messageLabelView = labelView;
// [labelView release];
}
}
- (void)dismissWithClickedButtonIndex:(NSInteger)buttonIndex animated:(BOOL)animated
{
if (buttonIndex >= 0 && buttonIndex < [_blocks count])
{
id obj = [[_blocks objectAtIndex: buttonIndex] objectAtIndex:0];
if (![obj isEqual:[NSNull null]])
{
((void (^)())obj)();
}
}
// there may be a better option to stop the execution thread inside the block obj above
if(buttonIndex == 0) {// or whatever index of Plus Button, dont removeView
return;
}
// code to removeView below, keep as usual
if (animated)
{
...
}
else
{
....
}
}
}
d. Change reloadAlert in ViewController.m
ViewController.m
-(void) reloadAlert {
value += 1;
alert.messageLabelView.text = [[[NSNumber alloc] initWithInteger:value ] stringValue];
[alert.messageLabelView setNeedsDisplay];
}
i have a custom cell for a table, is working fine,
Im showing a list of products in the cells, when the user touches a button "delete", i show an alert view to confirm deletion,
but I need to show the name of the product in the alert view: "are you sure you want to delete XXX?"
here the code for my custom cell
Please note the call to the alert view in deleteCartButtonPressed
#import "ShoppingCartProductsCell.h"
#import "Product.h"
#implementation ShoppingCartProductsCell
#synthesize categoryNameLabel = _categoryNameLabel;
#synthesize productNameLabel = _productNameLabel;
#synthesize quantityPicker = _quantityPicker;
#synthesize deleteCartButton = _deleteCartButton;
#synthesize product = _product;
- (void) dealloc {
[_deleteCartButton release];
[_categoryNameLabel release];
[_productNameLabel release];
[_quantityPicker release];
[super dealloc];
}
- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
//self = [super initWithFrame:frame];
self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
if (self) {
// Initialization code
[self initQuantityPicker];
[self initLabels]; //y picker!
[self initButtons];
}
return self;
}
- (void) initQuantityPicker {
CGRect contentRect = self.contentView.bounds;
CGFloat boundsX = contentRect.origin.x;
self.quantityPicker = [[[BDFDropDownList alloc] initWithFrame:CGRectMake(boundsX+220, 8, 61, 28) popupWidth:90]autorelease];
self.quantityPicker.delegate = self;
for (int i = 1; i<=20; i++) {
[self.quantityPicker addOptionWithName:[NSString stringWithFormat:#"%d",i] value:[NSNumber numberWithInt:i]];
}
[self.contentView addSubview:self.quantityPicker];
}
- (void) initLabels {
self.productNameLabel = [[[UILabel alloc]init] autorelease];
self.productNameLabel.textAlignment = UITextAlignmentLeft;
self.productNameLabel.backgroundColor = [UIColor clearColor];
self.productNameLabel.font = [UIFont fontWithName:#"HelveticaNeue" size:15];
self.productNameLabel.textColor = [UIColor colorWithRed:102/255.0f green:102/255.0f blue:102/255.0f alpha:1];
[self.contentView addSubview:self.productNameLabel];
}
- (void) initButtons {
self.deleteCartButton = [UIButton buttonWithType:UIButtonTypeCustom];
[self.deleteCartButton addTarget:self action:#selector(deleteCartButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
[self.deleteCartButton setImage:[UIImage imageNamed:#"deleteCartButton.png"] forState:UIControlStateNormal];
[self.contentView addSubview:self.deleteCartButton]; //Calculations For stage 2
}
- (void)layoutSubviews {
[super layoutSubviews];
CGRect contentRect = self.contentView.bounds;
CGFloat boundsX = contentRect.origin.x;
CGRect frame;
frame= CGRectMake(boundsX+10 ,10, 200, 20);
self.productNameLabel.frame = frame;
frame= CGRectMake(boundsX+330 ,8, 30, 29); //310
self.deleteCartButton.frame = frame;
}
- (void)setSelected:(BOOL)selected animated:(BOOL)animated
{
[super setSelected:selected animated:animated];
// Configure the view for the selected state
}
- (void) setProduct:(Product*)product {
[self setProduct:product withQuantity:0];
}
- (void) setProduct:(Product*)product withQuantity:(NSInteger)quantity {
[_product release];
_product = product;
[_product retain];
self.productNameLabel.text = product.SKU;
self.quantityPicker.delegate = nil;
[self.quantityPicker setSelectedIndex:quantity-1]; //testa
self.quantityPicker.delegate = self;
}
- (void) deleteCartButtonPressed:(id) sender {
NSLog(#"Delete ");
UIAlertView *deleteAlert = [[UIAlertView alloc]initWithTitle:#"Attention" message:#"Are you sure you want to delete this record?" delegate:nil cancelButtonTitle:#"Cancel" otherButtonTitles:#"Ok", nil];
[deleteAlert show];
[deleteAlert release];
}
#end
Thanks a lot!
string literals are your friend.
- (void) deleteCartButtonPressed:(id) sender {
NSLog(#"Delete ");
UIAlertView *deleteAlert = [[UIAlertView alloc]initWithTitle:#"Attention" message:[NSString stringWithFormat:#"Are you sure you want to delete %#?", [myTableDatasource objectAtIndex:idx]], delegate:nil cancelButtonTitle:#"Cancel" otherButtonTitles:#"Ok", nil];
[deleteAlert show];
[deleteAlert release];
}
It's probably best to move this out of your cell subclass and into your datasource and delegate so as to facilitate cleaner code.