Passing a value from a class to a cell - ios

In my app I'm using the PSCollectionView to create a view similar to pinterest. Now I'm trying to pass from my class to the cell class a value in which I insert the height of the imageView I set in the cell. When I run the app, the app create a cell exactly using this height, but the imageView has no dimension.
I post here my code:
PSCollectionView controller
- (CGFloat)collectionView:(PSCollectionView *)collectionView heightForRowAtIndex:(NSInteger)index {
NSString *width = [self.arrayWithData[index] objectForKey:#"width"];
NSString *height = [self.arrayWithData[index] objectForKey:#"height"];
NSLog(#"%# e %#", width, height);
cellHeight = [self getHeightWith:width andHeight:height];
return cellHeight;
}
- (CGFloat)getHeightWith:(NSString *)originalWidth andHeight:(NSString *)originalHeight {
float width = [originalWidth floatValue];
float height = [originalHeight floatValue];
float multiplier = height / width;
// So che la mia cella ha una dimensione massima in larghezza di 100, da questo calcolo l'altezza
return 100 * multiplier;
}
- (PSCollectionViewCell *)collectionView:(PSCollectionView *)collectionView cellForRowAtIndex:(NSInteger)index {
ProductViewCell *cell = (ProductViewCell *)[self.psView dequeueReusableViewForClass:nil];
if (!cell) {
//cell = [[ProductViewCell alloc]initWithFrame:CGRectMake(10, 70, 100, 100)];
//cell = [[ProductViewCell alloc] initWithFrame:CGRectMake(0,0,collectionView.frame.size.width/2,100)];
cell = [[ProductViewCell alloc] initWithFrame:CGRectMake(0,0,collectionView.frame.size.width/2,cellHeight + 20)];
}
cell.imageHeight = cellHeight;
cell.labelName.text = [[self.arrayWithData objectAtIndex:index]objectForKey:#"name"];
NSURL * url = [NSURL URLWithString:[[self.arrayWithData objectAtIndex:index]objectForKey:#"url"]];
[self loadImageFromWeb:url andImageView:cell.productImage];
return cell;
}
- (void) loadImageFromWeb:(NSURL *)urlImg andImageView:(UIImageView *)imageView {
//NSURLRequest* request = [NSURLRequest requestWithURL:url];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:urlImg];
NSString *authCredentials =#"reply:reply";
NSString *authValue = [NSString stringWithFormat:#"Basic %#",[authCredentials base64EncodedStringWithWrapWidth:0]];
[request setValue:authValue forHTTPHeaderField:#"Authorization"];
[NSURLConnection sendAsynchronousRequest:request
queue:[NSOperationQueue mainQueue]
completionHandler:^(NSURLResponse * response,
NSData * data,
NSError * error) {
if (!error){
UIImage *image = [[UIImage alloc] initWithData:data];
[imageView setImage:image];
[HUD hide:YES];
} else {
NSLog(#"ERRORE: %#", error);
}
}];
}
and this code:
ProductViewCell.h
#import "PSCollectionViewCell.h"
#interface ProductViewCell : PSCollectionViewCell {
float wMargin;
}
#property(nonatomic,strong)UIImageView *productImage;
#property(nonatomic,strong)UILabel *labelName;
// I use this variable to pass the height of the cell from the class who implement PSCollectionView
#property CGFloat imageHeight;
+ (CGFloat)heightForViewWithObject:(id)object inColumnWidth:(CGFloat)cloumnWidth;
#end
ProductViewCell.m
#import "ProductViewCell.h"
#define MARGIN 8.0
#implementation ProductViewCell
- (id)initWithFrame:(CGRect)frame
{
wMargin = 5.0;
self = [super initWithFrame:frame];
if (self) {
// self.productImage = [[UIImageView alloc]initWithFrame:CGRectMake(wMargin, 5, frame.size.width - (wMargin * 2), 125)];
self.productImage = [[UIImageView alloc]initWithFrame:CGRectMake(wMargin, 5, frame.size.width - (wMargin * 2), self.imageHeight)];
self.labelName = [[UILabel alloc]initWithFrame:CGRectMake(wMargin, 130, frame.size.width - (wMargin * 2), 20)];
self.labelName.font = [self.labelName.font fontWithSize:12];
self.labelName.textAlignment = NSTextAlignmentCenter;
[self addSubview:self.productImage];
[self addSubview:self.labelName];
self.backgroundColor = [UIColor colorWithRed:236.0f/255.0f green:236.0f/255.0f blue:236.0f/255.0f alpha:1.0];
self.layer.masksToBounds = YES;
self.layer.borderWidth = 1.0f;
self.layer.cornerRadius = 10.0f;
self.layer.borderColor= [[UIColor colorWithRed:207.0f/255.0f green:207.0f/255.0f blue:207.0f/255.0f alpha:1] CGColor];
[self.productImage setContentMode:UIViewContentModeScaleAspectFit];
}
return self;
}
/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect
{
// Drawing code
}
*/
#end
When I try to log the value of self.imageHeight it shows in the console a 0, but you can see that I set this data to cellHeight in the PSCollectionView controller.
How I can send the data I calculate to my cell? There's a way to do that?

According to the provided code, the class property imageHeight in the ProductViewCell implementation is only used when a new cell is initialized. At that time the imageHeight has never been set or updated, so it will always be 0.
This means whenever you update the value for imageHeight, the cell property will be updated, but the cell won't do anything with it.
To achieve that you can simply override the setImageHeight: method in ProductViewCell to be able to trigger some action.
- (void)setImageHeight:(CGFloat)imageHeight {
if (_imageHeight != imageHeight) {
_imageHeight = imageHeight;
// Do something useful with the new value e.g. calculations
}
}
This method will be called every time you update the cell property
cell.imageHeight = ...

Finally I did it without using setter! The solution is simply to use the frame.size.height. My cell code is the following:
- (id)initWithFrame:(CGRect)frame
{
wMargin = 5.0;
self = [super initWithFrame:frame];
if (self) {
self.productImage = [[UIImageView alloc]initWithFrame:CGRectMake(wMargin, 5, frame.size.width - (wMargin * 2), frame.size.height)];
self.labelName = [[UILabel alloc]initWithFrame:CGRectMake(wMargin, frame.size.height, frame.size.width - (wMargin * 2), 20)];
self.labelName.font = [self.labelName.font fontWithSize:12];
self.labelName.textAlignment = NSTextAlignmentCenter;
[self addSubview:self.productImage];
[self addSubview:self.labelName];
self.backgroundColor = [UIColor colorWithRed:236.0f/255.0f green:236.0f/255.0f blue:236.0f/255.0f alpha:1.0];
self.layer.masksToBounds = YES;
self.layer.borderWidth = 1.0f;
self.layer.cornerRadius = 10.0f;
self.layer.borderColor= [[UIColor colorWithRed:207.0f/255.0f green:207.0f/255.0f blue:207.0f/255.0f alpha:1] CGColor];
[self.productImage setContentMode:UIViewContentModeScaleAspectFit];
}
return self;
}
I simply used the frame.size.height to define the height of my imageView and following you can see the result:

Related

__block modifier creates unreadable memory

Now Im developing a banner showing feature in iOS
It's a singleton which shows banner on the upper part of screen when user logs in.
It's basically a shared view with a class method showWithName...
#interface XXUserWelcomeBanner ()
{
UIImageView *logoView;
UILabel *textLabel;
CGFloat _width;
}
#end
When user calls, it creates a UIImageView and a UILabel to add on self. And animates itself onto the screen.
+ (XXUserWelcomeBanner *)shared {
static dispatch_once_t onceToken;
static XXUserWelcomeBanner *userWelcomBanner;
dispatch_once(&onceToken, ^{
userWelcomBanner = [[XXUserWelcomeBanner alloc] init];
});
return userWelcomBanner;
}
+ (void)showWithUserName:(NSString *)userID andLogo:(UIImage * _Nullable)logo {
dispatch_async(dispatch_get_main_queue(), ^{
[[self shared] createWithName:userID andLogo:logo];
});
}
So there's this other bug I just found that causes this method to be called twice and on the second time it shows only the UIImageView.
And I don't understand why that's happening.
Because the UIImageView and UILabel won't be created twice.
Here's more code.
#pragma mark - private
- (void)createWithName:(NSString *)name andLogo:(UIImage * _Nullable)logo {
self.opaque = NO;
self.alpha = 0.9;
self.backgroundColor = COLOR(0xfcfcfc);
// if (#available(iOS 13.0, *)) {
// self.backgroundColor = UIColor.secondarySystemBackgroundColor;
// }
CGSize labelSize = CGSizeZero;
if (logoView == nil) {
if (logo != nil) {
logoView = [[UIImageView alloc] initWithImage:logo];
[self addSubview:logoView];
} else {
NSString *imagePath = [XXUtility pathForResourceNamed:#"Logo" withExtension:#"png"];
UIImage *imageToAdd = [[UIImage alloc] initWithContentsOfFile:imagePath];
logoView = [[UIImageView alloc] initWithImage:imageToAdd];
[self addSubview:logoView];
}
}
if (textLabel == nil) {
textLabel = [[UILabel alloc] init];
NSString * labelString = [NSString stringWithFormat:NSLocalizedStringWithDefaultValue(#"welcom banner", #"userInterface", [XXUtility bundleForStrings], #"Dear %#, welcome into game", #"user welcome banner text"), name];
labelSize = [labelString sizeWithAttributes:#{NSFontAttributeName : textLabel.font}];
textLabel.text = labelString;
[self addSubview:textLabel];
}
NSLog(#"XXUserWelcomeBanner Label size is %f x %f", labelSize.height, labelSize.width);
[self bannerSizeWithLabelSize:labelSize];
CGFloat bannerHeight = self.frame.size.height;
CGFloat bannerWidth = self.frame.size.width;
CGFloat logoHeight = bannerHeight * 0.45;
CGFloat logoWidth = logoHeight;
CGFloat logoXPos = (bannerWidth - logoWidth - labelSize.width) / 2;
CGFloat logoYPos = (bannerHeight - logoHeight) / 2;
CGFloat labelHeight = labelSize.height;
CGFloat labelWidth = labelSize.width;
CGFloat labelXPos = logoXPos + logoWidth + 5;
CGFloat labelYPos = (bannerHeight - labelHeight) / 2;
logoView.frame = CGRectMake(logoXPos, logoYPos, logoWidth, logoHeight);
textLabel.frame = CGRectMake(labelXPos, labelYPos, labelWidth, labelHeight);
[self bannerShow];
}
- (void)bannerSizeWithLabelSize:(CGSize)lSize {
_width = 40 + lSize.width + 5;
CGFloat height = 40;
CGFloat xPosition = ScreenWidth * 1/2 - _width * 1/2;
CGFloat yPosition = - height;
self.frame = CGRectMake(xPosition, yPosition, _width, height);
}
- (void)bannerShow {
UIViewController *vc;
if ([TOP_VIEWCONTROLLER respondsToSelector:#selector(topViewController)]) {
vc = [TOP_VIEWCONTROLLER topViewController];
} else {
vc = TOP_VIEWCONTROLLER;
}
[vc.view addSubview:self];
[UIView animateWithDuration:0.6 delay:0.2 options:UIViewAnimationOptionCurveEaseOut animations:^{
CGFloat height = 40;
CGFloat xPos = ScreenWidth * 1/2 - self->_width * 1/2;
CGFloat yPos = height * 1/3 + KiPhoneXSafeAreaDValue;
self.frame = CGRectMake(xPos, yPos, self->_width, height);
} completion:^(BOOL finished) {
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
[UIView animateWithDuration:0.6 delay:0.2 options:UIViewAnimationOptionCurveEaseIn animations:^{
CGFloat height = 40;
CGFloat xPosition = ScreenWidth * 1/2 - self->_width * 1/2;
CGFloat yPosition = - height;
self.frame = CGRectMake(xPosition, yPosition, self->_width, height);
} completion:^(BOOL finished) {
[self bannerDestroy];
self.alpha = 0;
}];
});
}];
}
- (void)bannerDestroy {
[logoView removeFromSuperview];
[textLabel removeFromSuperview];
logoView = nil;
textLabel = nil;
[self removeFromSuperview];
}
- (void)dealloc
{
//
NSLog(#"uiview dealloc");
}
/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
// Drawing code
}
*/
#end
Thanks in advance.
It is expected that createWithName:andLogo: is calling more than once in your app. I guess you call it with different arguments, that's why it should not be inside dispatch_once(&onceToken, ^{ });. But you can optimise XXUserWelcomeBanner's init:
- (instancetype)init {
self = [super init];
if (self) {
logoView = [[UIImageView alloc] init];
[self addSubview:logoView];
textLabel = [[UILabel alloc] init];
[self addSubview:textLabel];
}
return self;
}
In createWithName:andLogo: you will have the following:
if (logo != nil) {
logoView.image = logo;
} else {
NSString *imagePath = [XXUtility pathForResourceNamed:#"Logo" withExtension:#"png"];
UIImage *imageToAdd = [[UIImage alloc] initWithContentsOfFile:imagePath];
logoView.image = imageToAdd;
}
NSString * labelString = [NSString stringWithFormat:NSLocalizedStringWithDefaultValue(#"welcom banner", #"userInterface", [XXUtility bundleForStrings], #"Dear %#, welcome into game", #"user welcome banner text"), name];
CGSize labelSize = [labelString sizeWithAttributes:#{NSFontAttributeName : textLabel.font}];
textLabel.text = labelString;

How do i get custom UIView in table view cell

I have a Custom UIView inside my prototype cell in a nd iOS 8.2 app before it was a regular UIImage and i was getting it back fine with [currentCell viewWithTag:200]; inside my UITableView cellForRowIndexPath method. But after i have made a custom uiview and replaced the uiimage it always returns nil..
edit
After trying to add a new label to a working menu controller that is way more simple just loops over a array of strings. and setting the tag and in the loop (that is already printing the correct value out for the menu) it can't find the newly added label. is it possible to somehow not get the tags compiled ?
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *currentCell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
Lists *listItem = [lists objectAtIndex:indexPath.row];
if(currentCell == nil){
currentCell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
//THIS ALLWAYS RETUNS nil
ShadedBadgeImage *cellImage = (ShadedBadgeImage *)[currentCell viewWithTag:200];
//UIView *cellImage = (UIView *)[currentCell viewWithTag:200];
//cellImage.completedProcentage = 2.0 * listItem.id.doubleValue;
UILabel *cellTitle = (UILabel *) [currentCell viewWithTag:101];
UILabel *cellDescription = (UILabel *)[currentCell viewWithTag:102];
cellTitle.text = listItem.id.stringValue;
cellDescription.text = listItem.shortText;
return currentCell;
And my custom uiview. that is using the layoutSubviews to render the masked image and progress bar.
IB_DESIGNABLE
#implementation ShadedBadgeImage {
double lineWidth;
CAShapeLayer *backgroundLayer;
CAShapeLayer *coloredLayer;
CALayer *imageLayer;
}
- (void)baseInit {
lineWidth = 5.0;
[self updateStroke];
}
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
[self baseInit];
}
return self;
}
- (id)initWithCoder:(NSCoder *)aDecoder {
if ((self = [super initWithCoder:aDecoder])) {
[self baseInit];
}
return self;
}
- (void)layoutSubviews {
[super layoutSubviews];
//Adds the background ring layer
if(backgroundLayer == nil)
{
backgroundLayer = [[CAShapeLayer alloc] init];
CGRect rect = CGRectInset(self.bounds, lineWidth/2.0, lineWidth/2.0);
UIBezierPath *roundPath = [UIBezierPath bezierPathWithOvalInRect:rect];
backgroundLayer.path = roundPath.CGPath;
backgroundLayer.fillColor = nil;
backgroundLayer.lineWidth = lineWidth;
backgroundLayer.strokeColor = [UIColor colorWithWhite:0.5 alpha:0.05].CGColor;
[self.layer addSublayer:backgroundLayer];
}
backgroundLayer.frame = self.layer.frame;
//Adds the color ring layer
if(coloredLayer == nil)
{
coloredLayer = [[CAShapeLayer alloc] init];
CGRect rect = CGRectInset(self.bounds, lineWidth/2.0, lineWidth/2.0);
UIBezierPath *roundPath = [UIBezierPath bezierPathWithOvalInRect:rect];
coloredLayer.path = roundPath.CGPath;
coloredLayer.fillColor = nil;
coloredLayer.lineWidth = lineWidth;
coloredLayer.strokeColor = [UIColor blueColor].CGColor;
coloredLayer.anchorPoint = CGPointMake(0.5, 0.5);
coloredLayer.transform = CATransform3DRotate(coloredLayer.transform, -M_PI/2, 0, 0, 1);
[self.layer addSublayer:coloredLayer];
}
coloredLayer.frame = self.layer.frame;
//Adds the color ring layer
if(imageLayer == nil)
{
CAShapeLayer *imageMask = [[CAShapeLayer alloc] init];
CGRect insertBounds = CGRectInset(self.bounds, lineWidth + 3.0, lineWidth + 3.0);
UIBezierPath *innerPath = [UIBezierPath bezierPathWithOvalInRect:insertBounds];
imageMask.path = innerPath.CGPath;
imageMask.fillColor = [UIColor grayColor].CGColor;
imageMask.frame = self.bounds;
[self.layer addSublayer:imageMask];
imageLayer = [[CALayer alloc] init];
imageLayer.mask = imageMask;
imageLayer.frame = self.layer.frame;
imageLayer.backgroundColor =[UIColor grayColor].CGColor;
imageLayer.contentsGravity = kCAGravityResizeAspectFill;
[self.layer addSublayer:imageLayer];
}
[self updateStroke];
}
- (void) updateStroke{
if (coloredLayer != nil)
{
coloredLayer.strokeEnd = self.completedProcentage;
}
if(self.image != nil)
{
imageLayer.contents = (__bridge id)([self.image CGImage]);
}
}
#end
As the comments says, dont use tags go for custom UITableCellViews for more control

UIButton does not show up in custom UIView

I am banging my head on this but cannot figure out the issue.
I have a custom UIView: FKPoiMiniDetail and this is the implementation (FKPoiMiniDetail.m)
const static CGFloat kDialogLateralMargin = 15.0;
const static CGFloat kDialogHeight = 100.0;
const static CGFloat kDialogBottomMargin = 10.0;
const static CGFloat kBottomButtonHeight = 50.0;
#interface FKPoiMiniDetail ()
#property (nonatomic) float tabBarHeight;
#property (nonatomic) NSUInteger numberOfButtons;
#property (nonatomic) NSMutableArray *buttonBlocks;
#property (strong, nonatomic) PoI* myPoi;
#end
#implementation FKPoiMiniDetail
- (id) initWithTabBarHeight:(float)aTabBarHeight numberOfButtons:(NSUInteger)numButtons andPoi:(PoI*)aPoi{
if (self = [super init]) {
self.tabBarHeight = aTabBarHeight;
self.numberOfButtons = numButtons;
self.myPoi = aPoi;
self.buttonBlocks = [[NSMutableArray alloc] init];
[self configure];
}
return self;
}
and here I add the the buttons programmatically:
- (void) assignButton:(NSUInteger)index anImage:(UIImage*)image aText:(NSString*)text andCallback:(void(^)())cb{
if (index > self.numberOfButtons) {
ALog("ERROR: Index is greater than number of buttons");
return;
}
[self.buttonBlocks addObject:cb];
int imWidth = 20;
int imHeight = 20;
int imLabelSpacing = 8;
CGSize labelSize = [text sizeWithAttributes:#{NSFontAttributeName: [UIFont systemFontOfSize:17.0f]}];
CGFloat overallWidth = labelSize.width + imWidth + imLabelSpacing;
CGFloat test = self.bounds.size.width;
CGFloat buttonWidth = test / ((CGFloat) self.numberOfButtons);
int x = index * buttonWidth;
int y = self.frame.size.height - kBottomButtonHeight;
UIButton *buttonContainer = [[UIButton alloc] initWithFrame:CGRectMake(x,y,buttonWidth,kBottomButtonHeight)];
[buttonContainer addTarget:self action:#selector(buttonTouched:) forControlEvents:UIControlEventTouchUpInside];
buttonContainer.tag = index;
int firstImOrigin = x + (buttonWidth - overallWidth) / 2;
UIImageView *iv = [[UIImageView alloc] initWithFrame:CGRectMake(firstImOrigin, (kBottomButtonHeight - imHeight)/2, imWidth, imHeight)];
[iv setImage:image];
[buttonContainer addSubview:iv];
CGRect lR = CGRectMake(firstImOrigin + imWidth + imLabelSpacing, (kBottomButtonHeight - labelSize.height)/2, labelSize.width, labelSize.height);
UILabel *label = [[UILabel alloc] initWithFrame:lR];
label.text = text;
[buttonContainer addSubview:label];
[self addSubview:buttonContainer];
}
and this is the selector as the target of the UIButton:
- (void)buttonTouched:(UIButton*)b{
void (^ myblock)() = [self.buttonBlocks objectAtIndex:b.tag];
myblock();
}
Somewhere else I create this object and assign buttons like this:
FKPoiMiniDetail *md = [[FKPoiMiniDetail alloc] initWithTabBarHeight:self.tabBarController.tabBar.frame.size.height
numberOfButtons:2
andPoi:annotation.aPoI];
UIImage *im = [UIImage imageNamed:#"detail.png"];
[md assignButton:0 anImage:im aText:#"Dettagli" andCallback:^{
ALog("Button 0 pressed");
}];
[md assignButton:1 anImage:im aText:#"Naviga" andCallback:^{
ALog("Button 1 pressed");
}];
[self.mapView addSubview:md];
The second button is empty, but the strange thing is this: clicking inside the button the callback does execute...
Debugging seems useless:
The variables for the first button:
and the variables for the second button:
Any help is appreciated, thanks in advance!
"Decomposing" your FKPoiMiniDetail
FKPoiMiniDetail
View
buttonContainer1 - buttonContainer2 — buttonContainer3, etc
So what's inside a buttonContainer should always have the same "frames" whereas it's buttonContainer frame that changes, according to the number of buttons, since buttonContainer will be their superview.
So you declare:
int x = index * buttonWidth;
int y = self.frame.size.height - kBottomButtonHeight;
The'll help setting the buttonContainer frame.
But label and iv should not depend of them, only depend of the height and the width of [buttonContainer frame] since they seems to be centered.
I guess that from you code, if you do at the end [self addSubview:iv] and [self addSubview:label]; you may see them.
I've had problems with setting images on UIImageView in the past and my solution has been changing the order to this:
[buttonContainer addSubview:iv];
[iv setImage:image];
First adding he subview and then setting the image.

IOS RoundView make child ImageView to be rounded

I've created this custom UIView named RoundView:
#import <QuartzCore/QuartzCore.h>
#implementation RoundedView
+(UIColor *)grayUIColor {
return [UIColor colorWithRed:161.0/255.0 green:157.0/255.0 blue:164.0/255.0 alpha:1.0];
}
+(UIColor *)darkBlueUIColor {
return [UIColor colorWithRed:86.0/255.0 green:88.0/255.0 blue:87.0/255.0 alpha:1];
}
+(UIColor *)greenUIColor {
return [UIColor colorWithRed:51.0/255.0 green:141.0/255.0 blue:130.0/255.0 alpha:1];
}
- (id)initWithCoder:(NSCoder *)aDecoder {
self = [super initWithCoder:aDecoder];
if (self)
{
//add pico icon as default image
_defaultImage = [UIImage imageNamed:#"actionBar_pico_icon"];
_isCreated = NO;
}
return self;
}
-(UIView*)createRoundViewWithBorder:(UIColor*)borderColor andPaddingColor:(UIColor*)paddingColor{
_borderColor = borderColor;
_paddingBackgroundColor = paddingColor;
[self setViewAppearance];
[self addImageToView];
_isCreated = YES;
return self;
}
/**
Set the current view appearance
*/
-(void) setViewAppearance {
self.layer.borderWidth = 1.5;
self.layer.borderColor = [_borderColor CGColor];
self.backgroundColor = _paddingBackgroundColor;
}
-(void) addImageToView {
CGRect frame = CGRectMake(0, 0, self.frame.size.width - 5, self.frame.size.height - 5);
_imageView = [[UIImageView alloc] initWithFrame:frame];
//calculate center x
float x = (self.frame.size.width - _imageView.frame.size.width) / 2;
//calculate center y
float y = (self.frame.size.height - _imageView.frame.size.height) / 2;
//create new frame
frame = CGRectMake(x, y, _imageView.frame.size.width, _imageView.frame.size.height);
_imageView.image = _defaultImage;
_imageView.frame = frame;
_imageView.contentMode = UIViewContentModeScaleAspectFit;
[self addSubview:_imageView];
[self makeViewRounded:_imageView];
[self makeViewRounded:self];
}
-(UIView*) makeViewRounded:(UIView*)view {
//set the look of the image
view.layer.cornerRadius= self.frame.size.height /2;
view.layer.opaque = NO;
view.layer.masksToBounds = YES;
return view;
}
-(void)updateImage:(UIImage *)image {
_image = image;
_imageView.image = image;
}
-(void)reset {
[self updateImage:_defaultImage];
}
#end
an example for the output will be :
If you look closely you will notice that the border is a circle, but the image view has edges.
How can i make the Image smooth as well ?
self.imgViewbg.layer.cornerRadius = self.imgViewbg.frame.size.width / 2;
self.imgViewbg.clipsToBounds = YES;
u Can Try This Code. And Implement in your Project..
It Will Definetly Work.. for u
I think the problem seems to be here:
view.layer.cornerRadius= self.frame.size.height /2;
Try giving it a constant small number and see the change. May be the height/2 is not making a perfect circle. You can give a smaller value than height/2 and see the change. It a wild guess by watching your image.

Adding subviews to a UIView at initialization

In the initialization method for a UIView subclass I am adding several UIImageViews. When the view is rendered they are present in the subviews array and have valid frame rects, but are not drawn on the screen. Does anyone know why this happens?
- (id) initWithFrame:(CGRect)frame {
self = [super initWithFrame:frame];
if (!self)
return nil;
[self commonInit];
return self;
}
- (void) commonInit {
_padding = 128.0f;
// Add the chord views here
_chordImages = [NSArray arrayWithObjects:[UIImage imageNamed:#"fn_maj_x_x_x_x_1_e_1_fn"], [UIImage imageNamed:#"en_maj_x_x_x_x_1_e_1_en"], [UIImage imageNamed:#"dn_maj_x_x_x_x_1_d_1_f#"], [UIImage imageNamed:#"an_min_x_x_x_x_1_a_1_en"], nil];
CGFloat containerWidth = [self bounds].size.width;
NSLog(#"containerWidth: %f",containerWidth);
CGFloat chordWidth = [[_chordImages objectAtIndex:0] size].width;
NSLog(#"chordWidth: %f",chordWidth);
CGFloat chordMarkerWidth = [[[GVChordMarkerView alloc] initWithFrame:CGRectMake(0, 0, 12, 12)] frame].size.width;
NSLog(#"chordMarkerWidth: %f",chordMarkerWidth);
// [self setFrame:CGRectMake(chordXPosition, 0, [self bounds].size.width, [self bounds].size.height]);
CGFloat chordXPosition = 0;
CGFloat chordXSpacing = (containerWidth/4 - (chordMarkerWidth + chordWidth));
chordXPosition += containerWidth/4;
for (NSUInteger i = 0; i < [_chordImages count]; i++) {
chordXPosition += chordXSpacing;
CGRect chordImageViewFrame = CGRectMake(chordXPosition, 0, [[_chordImages objectAtIndex:0] size].width, [[_chordImages objectAtIndex:0] size].height);
UIImageView *chordImageView = [[UIImageView alloc] initWithFrame:chordImageViewFrame];
[self addSubview:chordImageView];
chordXPosition += (chordMarkerWidth + chordWidth);
}
NSLog(#"Finished");
}
Could it be that your UIImageview is just empty? Where did you add the image?

Resources