I have a custom view about alertView.
But when I init my alertView, it seem not set my awakeFromNib value of label.
What's wrong about my code?
I can't figure out this issue.
Thanks.
AlertView.h
#import <UIKit/UIKit.h>
NS_ASSUME_NONNULL_BEGIN
#interface AlertView : UIView
#property (weak, nonatomic) IBOutlet UILabel *labTitle;
#property (weak, nonatomic) IBOutlet UILabel *labMessage;
#property (weak, nonatomic) IBOutlet UIButton *btnCancel;
#property (weak, nonatomic) IBOutlet UIButton *btnConfirm;
#end
AlertView.m
#import "AlertView.h"
#interface AlertView ()
#property (weak, nonatomic) IBOutlet UIView *headerView;
#end
#implementation AlertView
-(id)initWithFrame:(CGRect)frame {
self = [super initWithFrame:frame];
if(!self){
return nil;
}
self = [[[NSBundle mainBundle] loadNibNamed:NSStringFromClass([self class])
owner:self
options:nil] firstObject];
self.frame = frame;
return self;
}
- (void)awakeFromNib{
[super awakeFromNib];
// custom label text not show.
self.labTitle.text = #"123";
self.labMessage.text = #"456";
[self.btnCancel setTitle:#"789"; forState:UIControlStateNormal];
[self.btnConfirm setTitle:#"111"; forState:UIControlStateNormal];
self.btnCancel.layer.cornerRadius = 5.f;
self.btnConfirm.layer.cornerRadius = 5.f;
self.headerView.layer.cornerRadius = 10;
}
#end
Viewcontroller.m
#interface Viewcontroller ()
#property AlertView * alertView;
#end
#implementation Viewcontroller
- (void)viewDidLoad {
[self popupView];
}
- (void)popupView{
CGRect viewSize = CGRectMake(16, 100, [[UIScreen mainScreen] bounds].size.width - 16 * 2, self.height);
self.alertView = [[ResultAlertView alloc] initWithFrame:viewSize];
self.alertView.layer.cornerRadius = 10;
[self SetShadowForView:self.alertView];
[self.alertView.btnConfirm addTarget:self action:#selector(cancelStartUsingView:) forControlEvents:UIControlEventTouchUpInside];
[self.alertView.btnCancel addTarget:self action:#selector(cancelStartUsingView:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:self.alertView];
}
- (IBAction)cancelStartUsingView:(UIButton *)sender{
//Btn also not work.
NSLog(#"123");
}
#end
you can use:
- (void)layoutSubviews {
[super layoutSubviews];
self.labTitle.text = #"123";
self.labMessage.text = #"456";
[self.btnCancel setTitle:#"789" forState:UIControlStateNormal];
[self.btnConfirm setTitle:#"111"forState:UIControlStateNormal];
self.btnCancel.layer.cornerRadius = 5.f;
self.btnConfirm.layer.cornerRadius = 5.f;
self.headerView.layer.cornerRadius = 10;
}
and call
- (void)viewDidLoad {
dispatch_async(dispatch_get_main_queue(), ^{
[self popupView];
});
}
Related
I have customized a tableview cell programmatically.
header file:
#import <UIKit/UIKit.h>
#class LoadingCell;
typedef NS_ENUM(NSUInteger, LoadingCellStyle) {
LoadingCellStyleSelection,
LoadingCellStyleTextField,
LoadingCellStyleImagePicker,
};
#interface LoadingCell : UITableViewCell
#property (nonatomic, strong) UIImageView* leftImageView;
#property (nonatomic, strong) UILabel* titleLabel;
#property (nonatomic, strong) UILabel* detailLabel;
#property (nonatomic, assign) LoadingCellStyle style;
-(instancetype)initWithStyle:(LoadingCellStyle)style;
#end
implementation file:
#import "LoadingCell.h"
#define itemHeight 44
#implementation LoadingCell
-(instancetype)initWithStyle:(LoadingCellStyle)style
{
self = [super initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:#"loadingStats"];
self.style = style;
[self.contentView addSubview:self.titleLabel];
[self.contentView addSubview:self.leftImageView];
if (self.style == LoadingCellStyleSelection) {
}
return self;
}
#pragma mark property setter
-(UILabel *)titleLabel
{
if (!_titleLabel) {
_titleLabel = [[UILabel alloc] init];
_titleLabel.textColor = COLOR_TEXT_GRAY;
_titleLabel.font = [UIFont systemFontOfSize:13];
}
return _titleLabel;
}
-(UILabel *)detailLabel
{
if (!_detailLabel) {
_detailLabel = [[UILabel alloc] init];
_detailLabel.textColor = COLOR_TEXT_GRAY;
}
return _detailLabel;
}
-(UIImageView *)leftImageView
{
if (!_leftImageView) {
_leftImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#"star"]];
}
return _leftImageView;
}
#pragma mark layouts
-(void)layoutSubviews
{
CGRect imageframe = CGRectMake(k_Margin, 0, itemHeight, itemHeight);
[self.leftImageView setFrame:imageframe];
[self.titleLabel setFrame:CGRectMake(CGRectGetMaxX(imageframe), 0, 100, itemHeight)];
[self.detailLabel setFrame:CGRectMake(CGRectGetMaxX(self.titleLabel.frame), 0, kScreen_Width-CGRectGetMaxX(self.titleLabel.frame)-50, itemHeight)];
}
#end
And the result is shown like
As you see, the cell separator is short on the right side.
self.separatorInset = UIEdgeInsetsMake(0, 0, 0, -100);
this method is able to work around but I think there is mistakes on my method to customizing the tableview cell.
Thank you
Solution: I missed
[super layoutSubviews];
inside my customized the layout methods.
I am new to coding and had some basic knowledge but i am building out my first app from a tutorial and have a issue i can't figure out and after a few days of looking figured i would just ask. I get an error in my implementation file when initializing the object in the view did load.
It says use of undeclared identifier. any help would be greatly appreciated.
Here is my view controller.m
#import "ViewController.h"
#implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
NSLog(#"titleLabel.text = %#", self.titleLabel.text);
self.bandObject = [[BandObject alloc] init];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
-(BOOL)textFieldShouldBeginEditing:(UITextField *)textField
{
return YES;
}
-(BOOL)textFieldShouldReturn:(UITextField *)textField
{
self.bandObject.name = self.nameTextField.text;
[self.nameTextField resignFirstResponder];
return YES;
}
-(BOOL)textFieldShouldEndEditing:(UITextField *)textField
{
self.bandObject.name =self.nameTextField.text;
[self saveBandObject];
[self.nameTextField resignFirstResponder];
return YES;
}
-(BOOL)textViewShouldBeginEditing:(UITextView *)textView
{
self.saveNotesButton.enabled = YES;
return YES;
}
-(BOOL)textViewShouldEndEditing:(UITextView *)textView
{
self.bandObject.notes = self.notesTextView.text;
[self.notesTextView resignFirstResponder];
self.saveNotesButton.enabled = NO;
return YES;
}
- (IBAction)saveNotesButtonTouched:(id)sender
{
[self textViewShouldEndEditing:self.notesTextView];
}
- (IBAction)ratingStepperValueChanged:(id)sender
{
self.ratingValueLabel.text = [NSString stringWithFormat:#"%g",self.ratingStepper.value];
self.bandObject.rating = (int)self.ratingStepper.value;
}
- (IBAction)tourStatusSegmentedControlValueChanged:(id)sender
{
self.bandObject.touringStatus = self.touringStatusSegmentedControl.selectedSegmentIndex;
}
- (IBAction)haveSeenLiveSwitchValueChanged:(id)sender
{
self.bandObject.haveSeenLive = self.haveSeenLiveSwitch.on;
}
#end
and here is my .h
#import <UIKit/UIKit.h>
#import "WBABand.h"
#interface ViewController : UIViewController <UITextFieldDelegate, UITextViewDelegate>
#property (nonatomic, strong) WBABand *bandObject;
#property (nonatomic, weak) IBOutlet UILabel *titleLabel;
#property (nonatomic, weak) IBOutlet UITextField *nameTextField;
#property (nonatomic, weak) IBOutlet UITextView *notesTextView;
#property (nonatomic, weak) IBOutlet UIButton *saveNotesButton;
#property (nonatomic, weak) IBOutlet UIStepper *ratingStepper;
#property (nonatomic, weak) IBOutlet UILabel *ratingValueLabel;
#property (nonatomic, weak) IBOutlet UISegmentedControl *touringStatusSegmentedControl;
#property (nonatomic, weak) IBOutlet UISwitch *haveSeenLiveSwitch;
- (IBAction)saveNotesButtonTouched:(id)sender;
- (IBAction)ratingStepperValueChanged:(id)sender;
- (IBAction)tourStatusSegmentedControlValueChanged:(id)sender;
- (IBAction)haveSeenLiveSwitchValueChanged:(id)sender;
#end
It is because you have an object in your .h called WBABand. And in your .m your are initializing a BandObject which does not exists.
Change this [[BandObject alloc] init];
to this [[WBABand alloc] init];
When you run into an issue, please try to narrow it down to the shortest code block possible to reproduce. At the very least, you should be pointing out the line that shows the error so that contributors can help you easier.
You are trying to instantiate an instance of BandObject, but the class you should be trying to instantiate is WBABand.
self.bandObject = [[WBABand alloc] init];
This is my first time dealing with annotations and callouts. I've got it working for the most part ( albeit, maybe not the correct way )
So, I have my mapView:
#interface MapViewController : BaseUIViewController
<MKMapViewDelegate, CLLocationManagerDelegate>
#property (strong, nonatomic) IBOutlet MKMapView *mapView;
#property (strong, nonatomic) NSMutableArray *friendsAnnotations;
#property (strong, nonatomic) NSMutableArray *friendsResults;
#property (strong, nonatomic) NSTimer *reloadTimer;
- (IBAction)zoomButtonPressed:(id)sender;
#property (strong, nonatomic) IBOutlet UIButton *zoomButton;
#end
The timer, I have set to reload the map every minute while you are on that screen. It calls these functions:
#pragma mark - Update Map Annotations
- (void) getFriendsForAnnotations {
[User syncUserWithCompletionHandler:^{
[ServerComm listCollection:UsersCollection withValues:[DEFAULTS objectForKey:userActiveFriendsKey] forKey:mongoIDKey withCompletionHandler:^(NSDictionary *response) {
[self.mapView removeAnnotations:self.friendsAnnotations];
[self.friendsAnnotations removeAllObjects];
self.friendsResults = [[response objectForKey:#"results"] mutableCopy];
dispatch_group_t group = dispatch_group_create();
for (id userDic in self.friendsResults) {
User *theUser = [User userFromDictionary:userDic];
dispatch_group_enter(group);
if ([[userDic objectForKey:userPrivacyLevelKey] integerValue] == 0 ||
[[userDic objectForKey:userPrivacyLevelKey] integerValue] == 1
){
NSDictionary *locationDic = [userDic objectForKey: userLastLocationKey];
BOOL checkedIn = FALSE;
if(![theUser.checkedInLocationName isEqualToString:EMPTYSTRING]) {
checkedIn = TRUE;
}
CustomAnnotation *CA = [[CustomAnnotation alloc] initWithTitle:[userDic objectForKey:userUsernameKey] Location:CLLocationCoordinate2DMake([[locationDic objectForKey:#"latitude"] doubleValue], [[locationDic objectForKey:#"longitude"] doubleValue]) UserImage:[userDic objectForKey:userProfilePictureURLKey] isCheckedIn:checkedIn];
[CA setCalloutUser:theUser];
[self.friendsAnnotations addObject: CA];
}
dispatch_group_leave(group);
}
dispatch_group_notify(group, dispatch_get_main_queue(), ^{
[self plotAnnotationsOnMap:self.friendsAnnotations];
});
}];
}];
}
- (void) plotAnnotationsOnMap: (NSArray *) arrayOfLocations {
[self.mapView addAnnotations: self.friendsAnnotations];
}
The point to this, is to setup the initial annotation for use with the standard initWithAnnotation method.
The final step to plotting our annotations on the map is the viewForAnnotation method:
- (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id<MKAnnotation>)annotation {
if ([annotation isKindOfClass:[CustomAnnotation class]]) {
CustomAnnotation *myAnnotation = ((CustomAnnotation *)annotation);
CustomAnnotation *annotationView = (CustomAnnotation *) [self.mapView dequeueReusableAnnotationViewWithIdentifier:#"customAnnotation"];
if (annotationView == nil) {
annotationView = [[CustomAnnotation alloc] initWithAnnotation:myAnnotation.annotation reuseIdentifier:#"customAnnotation"];
}
[annotationView setAnnotation:annotation];
[annotationView.userImage sd_setImageWithURL:[NSURL URLWithString:myAnnotation.userImageString]];
[annotationView setUserImageString:myAnnotation.userImageString];
[annotationView setCalloutUser:myAnnotation.calloutUser];
if (myAnnotation.isCheckedIn) {
annotationView.markerImage.image = [annotationView.markerImage.image imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate];
[annotationView.markerImage setTintColor:COLOR_BLUE_MUTED];
} else {
annotationView.markerImage.image = [annotationView.markerImage.image imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate];
[annotationView.markerImage setTintColor:COLOR_GREY_LIGHT];
}
annotationView.centerOffset = CGPointMake(0, -39);
annotationView.rightCalloutAccessoryView = [UIButton buttonWithType: UIButtonTypeDetailDisclosure];
annotationView.canShowCallout = NO;
return annotationView;
} else {
return nil;
}
}
This annotation is defined with a CustomAnnotation.h/m file as you would normally expect, and is pulled in from a xib.
#import <Foundation/Foundation.h>
#import "CustomAnnotationCallout.h"
#import <MapKit/MapKit.h>
#interface CustomAnnotation : MKAnnotationView <MKAnnotation>
#property (nonatomic, assign) IBOutlet UIView* loadedView;
#property (nonatomic, strong) User *calloutUser;
#property (nonatomic, strong) UIView *calloutView;
#property (retain, nonatomic) IBOutlet UIImageView *markerImage;
#property (retain, nonatomic) IBOutlet UIImageView *userImage;
#property (retain, nonatomic) NSString *userImageString;
#property (copy, nonatomic) NSString *title;
#property (nonatomic, assign) CLLocationCoordinate2D coordinate;
#property (assign, nonatomic) BOOL isCheckedIn;
#property (assign, nonatomic) BOOL showCustomCallout;
#property (assign, nonatomic) CGRect endFrame;
- (id) initWithTitle:(NSString *)newTitle Location:(CLLocationCoordinate2D)location UserImage:(NSString *)userImageString isCheckedIn:(BOOL)checkedIn;
- (void) setShowCustomCallout:(BOOL)showCustomCallout;
- (void) setShowCustomCallout:(BOOL)showCustomCallout animated:(BOOL)animated;
#end
and the .m file:
#import "CustomAnnotation.h"
#import "CustomAnnotationCallout.h"
#import "Utilities.h"
#import "UIImageView+WebCache.h"
#implementation CustomAnnotation
- (id) initWithTitle:(NSString *)newTitle Location:(CLLocationCoordinate2D)location UserImage:(NSString *)userImageString isCheckedIn:(BOOL)checkedIn{
self = [super init];
[[NSBundle mainBundle] loadNibNamed:#"AnnotationView" owner:self options:nil];
if (self) {
if (_loadedView) {
_loadedView.frame = CGRectMake(_loadedView.frame.origin.x, _loadedView.frame.origin.y, 80, 80);
[self addSubview:_loadedView];
self.userImageString = userImageString;
}
self.userImageString = userImageString;
_title = newTitle;
_coordinate = location;
self.isCheckedIn = checkedIn;
self.enabled = YES;
self.canShowCallout = NO;
self.image = [UIImage imageNamed:#"icon_clear"];
self.frame = CGRectMake(self.frame.origin.x, self.frame.origin.y, 80, 80);
self.rightCalloutAccessoryView = [UIButton buttonWithType:UIButtonTypeDetailDisclosure];
}
return self;
}
- (id)initWithAnnotation:(id <MKAnnotation>)annotation reuseIdentifier:(NSString*)reuseIdentifier
{
self = [super initWithAnnotation:annotation reuseIdentifier:reuseIdentifier];
if (self != nil)
{
[[NSBundle mainBundle] loadNibNamed:#"AnnotationView" owner:self options:nil];
if (_loadedView){
_loadedView.frame = CGRectMake(_loadedView.frame.origin.x, _loadedView.frame.origin.y, 80, 80);
[self addSubview:_loadedView];
}
self.enabled = YES;
self.canShowCallout = NO;
self.image = [UIImage imageNamed:#"icon_clear"];
self.frame = CGRectMake(self.frame.origin.x, self.frame.origin.y, 80, 80);
self.rightCalloutAccessoryView = [UIButton buttonWithType:UIButtonTypeDetailDisclosure];
}
return self;
}
- (void) setShowCustomCallout:(BOOL)showCustomCallout {
[self setShowCustomCallout:showCustomCallout animated:NO];
}
- (void) setShowCustomCallout:(BOOL)showCustomCallout animated:(BOOL)animated {
if (_showCustomCallout == showCustomCallout) return;
_showCustomCallout = showCustomCallout;
void (^animationBlock)(void) = nil;
void(^completionBlock)(BOOL finished) = nil;
if (_showCustomCallout) {
self.calloutView.alpha = 0.0f;
animationBlock = ^ {
self.calloutView.alpha = 1.0f;
[self addSubview:self.calloutView];
};
} else {
animationBlock = ^{ self.calloutView.alpha = 0.0f; };
completionBlock = ^(BOOL finished) { [self.calloutView removeFromSuperview]; };
}
if (animated) {
[UIView animateWithDuration:0.2f animations:animationBlock completion:completionBlock];
} else {
animationBlock();
completionBlock(YES);
}
}
#end
Now, if we click on the annotation we get our custom callout:
MapViewController Code:
- (void) mapView:(MKMapView *)mapView didSelectAnnotationView:(MKAnnotationView *)view {
if ([view isKindOfClass:CustomAnnotation.class]) {
CustomAnnotation *annotationView = (CustomAnnotation *)view;
CustomAnnotationCallout *callout = [CustomAnnotationCallout new];
callout.userImageString = annotationView.userImageString;
[callout.userImage sd_setImageWithURL:[NSURL URLWithString:callout.userImageString]];
[callout.nameLabel setText:[NSString stringWithFormat:#"%# #%#", annotationView.calloutUser.name, annotationView.calloutUser.username]];
[callout setUserID:annotationView.calloutUser.userID];
annotationView.calloutView = callout.loadedView;
annotationView.calloutView.center = CGPointMake(annotationView.bounds.size.width*0.5f, -annotationView.calloutView.bounds.size.height*0.5f);
[annotationView setShowCustomCallout:YES animated:YES];
CGRect annotationViewWithCalloutViewFrame = annotationView.frame;
annotationViewWithCalloutViewFrame.size.width += annotationView.calloutView.frame.size.width;
annotationViewWithCalloutViewFrame.size.height += annotationView.calloutView.frame.size.height;
CGRect mapRect = [self.mapView convertRegion:self.mapView.region toRectToView:self.mapView];
mapRect.origin.y = annotationView.frame.origin.y-annotationView.calloutView.frame.size.height;
mapRect.origin.x = annotationView.frame.origin.x+annotationView.calloutView.frame.origin.x;
MKCoordinateRegion finalRegion = [self.mapView convertRect:mapRect toRegionFromView:self.mapView];
[self.mapView setRegion:finalRegion animated:YES];
[self.mapView setScrollEnabled:NO];
[self.mapView setZoomEnabled:NO];
[self.reloadTimer invalidate];
}
}
CustomAnnotationCallout is also pulled in from a xib.
#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>
#interface CustomAnnotationCallout : UIView
#property (strong, nonatomic) IBOutlet UIView *loadedView;
#property (strong, nonatomic) IBOutlet UIImageView *userImage;
#property (assign, nonatomic) NSString *userImageString;
#property (strong, nonatomic) IBOutlet UILabel *nameLabel;
#property (strong, nonatomic) NSString *userID;
- (IBAction)profilePressed:(id)sender;
- (IBAction)button1:(id)sender;
- (IBAction)button2:(id)sender;
#end
and the .m:
#import "CustomAnnotationCallout.h"
#implementation CustomAnnotationCallout
- (instancetype)init {
[[NSBundle mainBundle] loadNibNamed:#"CustomAnnotationCallout" owner:self options:nil];
_loadedView.frame = CGRectMake(_loadedView.frame.origin.x, _loadedView.frame.origin.y, [[UIScreen mainScreen] bounds].size.width, 178.0);
return self;
}
- (IBAction)profilePressed:(id)sender {
}
- (IBAction)button1:(id)sender {
}
- (IBAction)button2:(id)sender {
}
#end
Now, when we select the annotation our custom callout changes and the map repositions itself to where I selected. And we get this view:
Now that you see that what I have does work, and what i'm going for. The problem that I'm having, is figuring out how to get the button(s) on the callout to perform a specific task when clicked.
I've googled and read about hitTest, but couldn't figure out anything specifically on how to implement it properly especially when looking to get it to work on specific elements.
I've been at this from start to finish this entire week and this is where I'm stuck. Please note I've been doing iOS development for a total of about 4 months so I'm still relatively new.
I have some labels on UITableviewcell I want to change the label font in the setter but from some odd reason in
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
When I debugging I can see nothing inside the cell get allocated.
When I drop the setters everything work fine but with system font which I don't want to use.
Cell.h file
#import <UIKit/UIKit.h>
#interface CheckoutCell : UITableViewCell
#property (weak, nonatomic) IBOutlet UILabel *labelQuantity;
#property (weak, nonatomic) IBOutlet UILabel *labelMainDescription;
#property (weak, nonatomic) IBOutlet UILabel *labelCountName;
#property (weak, nonatomic) IBOutlet UILabel *labelInchSize;
#property (weak, nonatomic) IBOutlet UILabel *labelMMsize;
#property (weak, nonatomic) IBOutlet UILabel *labelStaticTotal;
#property (weak, nonatomic) IBOutlet UILabel *labelTotalPrice;
#property (weak, nonatomic) IBOutlet UILabel *label_ItemPrice;
#property (weak, nonatomic) IBOutlet UIButton *btnBuyAnotherProduct;
#property (weak, nonatomic) IBOutlet UIButton *btnAddAnotherSet;
#end
cell.m file
#import "CheckoutCell.h"
#implementation CheckoutCell
- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
if (self) {
// Initialization code
}
return self;
}
- (void)setSelected:(BOOL)selected animated:(BOOL)animated
{
[super setSelected:selected animated:animated];
// Configure the view for the selected state
}
-(void) setLabelCountName:(UILabel *)labelCountName
{
[self setLabel:labelCountName];
}
-(void) setLabelMMsize:(UILabel *)labelMMsize
{
[self setLabel:labelMMsize];
}
-(void) setLabel_ItemPrice:(UILabel *)label_ItemPrice
{
[self setLabel:label_ItemPrice];
}
-(void) setLabelInchSize:(UILabel *)labelInchSize
{
[self setLabel:labelInchSize];
}
-(void) setLabelMainDescription:(UILabel *)labelMainDescription
{
[labelMainDescription setFont:[UIFont fontWithName:#"MuseoSans-500" size:14]];
}
-(void) setLabelQuantity:(UILabel *)labelQuantity
{
[labelQuantity setFont:[UIFont fontWithName:#"MuseoSans-500" size:18]];
}
-(void) setLabelTotalPrice:(UILabel *)labelTotalPrice
{
[labelTotalPrice setFont:[UIFont fontWithName:#"MuseoSans-500" size:14]];
}
-(void) setLabelStaticTotal:(UILabel *)labelStaticTotal
{
[labelStaticTotal setFont:[UIFont fontWithName:#"MuseoSans-500" size:14]];
}
//BTN setters
-(void) setBtnAddAnotherSet:(UIButton *)btnAddAnotherSet
{
[btnAddAnotherSet.titleLabel setFont:[UIFont fontWithName:#"MuseoSans-500" size:12]];
btnAddAnotherSet.titleLabel.textAlignment = UIBaselineAdjustmentAlignCenters;
}
-(void) setBtnBuyAnotherProduct:(UIButton *)btnBuyAnotherProduct
{
[btnBuyAnotherProduct.titleLabel setFont:[UIFont fontWithName:#"MuseoSans-500" size:12]];
btnBuyAnotherProduct.titleLabel.textAlignment = UIBaselineAdjustmentAlignCenters;
}
//generic setter
-(void) setLabel:(UILabel *)label
{
[label setFont:[UIFont fontWithName:#"MuseoSans-300" size:10]];
}
#end
I believe you should just set the text of the label not create and set the label again. for example
-(void) setLabelCountName:(UILabel *)labelCountName{
[self setLabel:labelCountName];
}
should be
-(void) setLabelCountName:(NSString *)labelCountName{
[self.labelCountName setText:labelCountName];
}
also you should change the Font in StoryBoard designer or in initWith... method.
I have a a class I created to generate UIButton's I add to my UIView. This worked great until my conversion to ARC yesterday, not I get the following error:
-[OrderTypeButton performSelector:withObject:withObject:]: message sent to deallocated instance 0x12449f70
Here is the code to add the button to my UIView (actually a subview in my main UIView):
OrderTypeButton *btn = [[OrderTypeButton alloc]initWithOrderType:#"All Orders" withOrderCount:[NSString stringWithFormat:#"%i",[self.ordersPlacedList count]] hasOpenOrder:NO];
btn.view.tag = 6969;
btn.delegate = self;
[btn.view setFrame:CGRectMake((col * width)+ colspacer, rowHeight + (row * height), frameWidth, frameHeight)];
[self.statsView addSubview:btn.view];
And here is my class header:
#import <UIKit/UIKit.h>
#protocol OrderTypeButtonDelegate
-(void) tapped:(id)sender withOrderType:(NSString*) orderType;
#end
#interface OrderTypeButton : UIViewController {
id<OrderTypeButtonDelegate> __unsafe_unretained delegate;
IBOutlet UILabel *lblOrderType;
IBOutlet UILabel *lblOrderCount;
NSString *orderType;
NSString *orderCount;
BOOL hasOpenOrder;
}
#property (nonatomic, strong) IBOutlet UIButton *orderButton;
#property (nonatomic, strong) IBOutlet UILabel *lblOrderType;
#property (nonatomic, strong) IBOutlet UILabel *lblOrderCount;
#property (nonatomic, strong) NSString *orderType;
#property (nonatomic, strong) NSString *orderCount;
#property (nonatomic, assign) BOOL hasOpenOrder;
#property (nonatomic, unsafe_unretained) id<OrderTypeButtonDelegate> delegate;
-(id) initWithOrderType: (NSString *) anOrderType withOrderCount: (NSString *) anOrderCount hasOpenOrder: (BOOL) openOrder;
-(IBAction)btnTapped:(id)sender;
#end
Implementation:
#import "OrderTypeButton.h"
#implementation OrderTypeButton
#synthesize orderButton;
#synthesize lblOrderType, lblOrderCount, orderType, orderCount, hasOpenOrder, delegate;
-(id) initWithOrderType: (NSString *) anOrderType withOrderCount: (NSString *) anOrderCount hasOpenOrder: (BOOL) openOrder {
if ((self = [super init])) {
self.orderType = anOrderType;
self.orderCount = anOrderCount;
self.hasOpenOrder = openOrder;
}
return self;
}
- (void)didReceiveMemoryWarning
{
// Releases the view if it doesn't have a superview.
[super didReceiveMemoryWarning];
}
#pragma mark - View lifecycle
- (void)viewDidLoad
{
[super viewDidLoad];
self.lblOrderType.text =[NSString stringWithFormat:#"%#", self.orderType];
self.lblOrderCount.text = [NSString stringWithFormat:#"%#", self.orderCount];
if (self.hasOpenOrder) {
[self.orderButton setBackgroundImage:[UIImage imageNamed:#"background-order-btn-red.png"] forState:UIControlStateNormal];
self.lblOrderType.textColor = [UIColor whiteColor];
self.lblOrderCount.textColor = [UIColor whiteColor];
}
}
-(IBAction)btnTapped:(id)sender {
NSLog(#"TAPPED");
if ([self delegate] ) {
[delegate tapped:sender withOrderType:self.orderType];
}
}
- (void)viewDidUnload
{
[self setOrderButton:nil];
[super viewDidUnload];
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
return YES;
}
#end
This seems fairly simple what I am doing here, not sure what changed with ARC that is causing me problems.
Maybe ARC autorelease created button, try to store created buttons in Array
//.h file
#property (nonatomic, strong) NSArray *buttonsArray
//.m file
#synthesize buttonsArray
...
- (void)viewDidLoad {
buttonsArray = [NSArray array];
...
OrderTypeButton *btn = [[OrderTypeButton alloc]initWithOrderType:#"All Orders"
withOrderCount:[NSString stringWithFormat:#"%i",[self.ordersPlacedList count]]
hasOpenOrder:NO];
btn.view.tag = 6969;
btn.delegate = self;
[btn.view setFrame:CGRectMake((col * width)+ colspacer, rowHeight + (row * height), frameWidth, frameHeight)];
[self.statsView addSubview:btn.view];
//Add button to array
[buttonsArray addObject:btn];
Also this approach will help if you want to change buttons, or remove some specific button from view