Access the UIImageView of the background image of a UIButton - ios

I have a UIButton, and I would like to access the UIImageView of its background image so that I can make the image circular. I know that I can affect the image itself but I would prefer to do this more elegantly. I also know that I can use the button.currentBackgroundImage property to get the UIImage in the background, but I want the view itself. Once I have the view I intend to use this code:
buttonImageView.layer.cornerRadius = buttonImageView.frame.size.width / 2;
buttonImageView.clipsToBounds = YES;
How can I access the buttonImageView?
EDIT:
Due to #vhristoskov's suggestions, I tried cropping the button itself with this code:
self.button.layer.cornerRadius = self.button.frame.size.width/2;
self.button.clipsToBounds = YES;
And it made this shape:
After debugging I found that frame.size.width was 46, when it should have been 100. So I tried this code instead:
self.button.layer.cornerRadius = self.button.currentBackgroundImage.size.width/2;
self.button.clipsToBounds = YES;
And that produced this shape:
And this time, the cornerRadius was being set to 65. So it actually seems like my problem is that I don't have the correct width at the moment. Which property should I access to get the correct number?

Well as I guessed and as you've already found - the problem is in the button size. To be sure that your button's size at runtime is what you expected to be - review your constraints. In the example below the button has vertical and horizontal central alignment and fixed width and height.
Constraints:
To have perfectly circular button you should have button.width == button.height. If this condition is met your code should work like a charm:
self.button.layer.cornerRadius = CGRectGetWidth(self.button.frame) / 2;
self.button.clipsToBounds = YES;

Assuming that you called something like:
[self.myButton setBackgroundImage:[UIImage imageNamed:#"image"] forState:UIControlStateNormal];
in viewDidLoad or earlier, you can then call the following in viewDidAppear:
if (self.myButton.subviews.count > 0 && [self.myButton.subviews[0] isKindOfClass:[UIImageView class]]) {
UIImageView *imageView = self.myButton.subviews[0];
imageView.layer.cornerRadius = imageView.frame.size.width / 2;
imageView.clipsToBounds = YES;
}
but it is not more elegant as the subview ordering is an implementation detail of UIButton and may change at any time.

Related

UIButton Label Showing 0 Width

I've got a Custom Button class that I'm setting up the text for in my storyboard file. The text is a simple "Update Email Address" and does not change throughout the life of the app.
However, I have an image I want to add to the button, and when I do that, I set the image in the following way, in a method inside the common button class:
[self setTintColor:[UIColor whiteColor]];
UIImage *icon = [UIImage imageNamed:iconName];
CGFloat iconWidth = icon.size.width;
[self setImage:icon forState:UIControlStateNormal];
[self setWidth:self.width+iconWidth*2];
[self setOriginX:self.x-iconWidth];
[self setTitleEdgeInsets:UIEdgeInsetsMake(0, -iconWidth*2, 0, 0)];
CGFloat leftMargin = 10;
CGFloat moveLeft = self.titleLabel.frame.size.width + self.titleLabel.x + leftMargin;
[self setImageEdgeInsets:UIEdgeInsetsMake(0, moveLeft , 0, 0)];
However, by setting it this way, it appears the titleLabel's width is 0 so the image isn't being set in the correct location on the button.
My thoughts on why this are happening are potentially because I never set the text programmatically, only in the storyboard, although that really doesn't make sense, it's all I got.
Does anyone see anything wrong here? If you need any other code let me know and I can post up the relevant info.
When do you do this? Maybe you are trying to do this after the resource was loaded but before the frames of all the elements are set.

viewWithTag can Use limited Time

I have 3 UIImageView as Thumbnails with tags: 1, 2, 3.
The following method:
- (IBAction)showImage:(UIGestureRecognizer *)sender
{
if (sender.view.layer.borderColor != [UIColor redColor].CGColor)
{
sender.view.layer.borderColor = [UIColor redColor].CGColor;
UIImageView *showFullImage = (UIImageView *)[self.view viewWithTag:sender+10];
[self.view addSubview:showFullImage];
showFullImage setTag:sender+20;
showFullImage.hidden = NO;
}
else
{
sender.view.layer.borderColor = [UIColor whiteColor].CGColor;
UIImageView *hideFullImage = (UIImageView *)[self.view viewWithTag:sender+20];
[hideFullImage removeFromSuperView];
hideFullImage.hidden = YES;
}
So, as you can see, I have 3 UIImageView small, thumbnails, with whiteBorderColor.
Also I have created and added to superView another 3 Images Full Size, same frame, and following tags: 11, 12, 13 also those images are hidden.
Now, I use the above code for this idea:
When I touch one of those 3 thumbnails, the borderColor will be red, and the hidden Full Size image which has tag = thumbnail.tag + 10, will be Visible. If I press again the same thumbnail image, what now has red borderColor, the Full Size image will be hidden, and the border will be white.
The code works, but my problem is: I can show and hide each Full Size image ONLY Twice.
THE IDEA IS THAT THUMBNAILS SHOULD WORK LIKE UIButton with pressed and normal states.
I don't want to use UIButtons.
Thanks
If i understood truely, you must not write below lines.
[self.view addSubview:showFullImage];
and
[hideFullImage removeFromSuperView];
Also you reset tag after hide.
[hideFullImage setTag:sender+10];
You add view and hide before you call showImage.
Sound like you forgot to reset your image try this:
UIImageView *hideFullImage = (UIImageView *)[self.view viewWithTag:sender+20];
[hideFullImage removeFromSuperView];
[hideFullImage setTag:sender+10];
hideFullImage.hidden = YES;

iOS: Autolayout causing UIScrollView to not scroll

I have set up a UIScrollView with which I want to display 12 images (only 8 fit on screen) laid out horizontally. In the following image you can see the problem I'm having (which makes my scroll view not scroll), my constraints and the UIScrollView which I have added on storyboard:
I have called the following method on -(void)viewDidLoad, where I "set up"my scrollview (itemList is my scroll view property and itemNames a array with the images'names):
- (void)setupHorizontalScrollView
{
self.itemList.delegate = self;
[self.itemList setTranslatesAutoresizingMaskIntoConstraints:NO];
[self.itemList setBackgroundColor:[UIColor blackColor]];
[self.itemList setCanCancelContentTouches:NO];
self.itemList.indicatorStyle = UIScrollViewIndicatorStyleWhite;
self.itemList.clipsToBounds = NO;
self.itemList.scrollEnabled = YES;
self.itemList.pagingEnabled = NO;
NSInteger tot=0;
CGFloat cx = 0;
for (; ; tot++) {
if (tot==12) {
break;
}
UIImageView *imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:[self.itemNames objectAtIndex:tot]]];
CGRect rect = imageView.frame;
rect.size.height = 40;
rect.size.width = 40;
rect.origin.x = cx;
rect.origin.y = 0;
imageView.frame = rect;
[self.itemList addSubview:imageView];
cx += imageView.frame.size.width;
}
[self.itemList setContentSize:CGSizeMake(cx, [self.itemList bounds].size.height)];
}
I have added the [self.itemList setTranslatesAutoresizingMaskIntoConstraints:NO]; because I saw this suggestion on other posts, but it doesn't work with or without it. The only way it works is if I uncheck use AutoLayout on the storyboard, but that moves the UIImageViewI use to look as a navigation bar to the bottom of the screen.
I don't know what to do anymore, any help is appreciated :)
Try to set your scrollView's Content size int "viewDidLayoutSubviews" method with keeping the autolayouts set.
-(void)viewDidLayoutSubviews
{
[self.itemList setContentSize:CGSizeMake(required_width, required_height)];
}
Two Solutions:
Create different constraints that can be satisfied simultaneously (you will have to edit). I think the problem is your bottom space and top space constraints are mutually exclusive. please remove one and try again. IF this is difficult for you, try adding another UIView to contain the UIScrollView to help manage your constraints, it might seem odd at first, but sometimes adding another view to contain your view actually makes it simpler at each level.
Turn off Autolayout, and change the autoresize masks of your UIImageView to be what you wish.
Insert: [scrollView setContentSize:CGSizeMake(x,y)]; in the following method:
-(void)viewWillAppear:(BOOL)animated

custom font on UIbutton title clipped on top of word

I have uploaded a custom font and applied this font on the title of a UIbutton using the following code
videoButton.titleLabel.font = [UIFont fontWithName:#"LaurenScript" size:20];
The problem is that the title is being clipped on the top of the first letter (see photo below). I tried the same font on the UIlabel and it works fine so it is not a problem with the font. I tried also to change the rectFrame using
[videoButton.titleLabel setFrame:CGRectMake(0, 0, 300, 600)];
but that didn't do anything.
Has anybody a clue of how I can fix this problem?
Cheers
I had a similar problem, where a diaeresis got cut off on top of the titlelabel.
I made a UIButton subclass and used this code to fix the problem:
-(void)layoutSubviews
{
[super layoutSubviews];
CGRect frame = self.titleLabel.frame;
frame.size.height = self.bounds.size.height;
frame.origin.y = self.titleEdgeInsets.top;
self.titleLabel.frame = frame;
}
Select button in Interface builder and check for set a vertical alignment panel in the control section Below is example:
Not sure if this is still an issue for anyone, but I found that (with using a custom font) the above solutions did not ultimately fix the issue, especially for a custom UIButton created solely programmatically.
Here is how I managed to fix this issue, with 1 line in particular that resolved the clipping issue:
UIButton *button = [[UIButton alloc] init];
button = [UIButton buttonWithType:UIButtonTypeCustom];
[button setTitle:#"Nice!" forState:UIControlStateNormal];
[button setFont:[UIFont fontWithName:<CUSTOM FONT NAME> size:buttonWidth/3.0f]];
button = CGRectMake(0, 0, <WIDTH>, <HEIGHT>);
Here was the line that resolved the clipping:
[button setContentVerticalAlignment:UIControlContentVerticalAlignmentFill];
Hopefully this helps anyone else who still were stuck. Happy coding!
had same problem using a button with an image and text with a custom font.
Everything had to be align centered vertically. And image not stretched.
this worked out fine for me.
btn.contentVerticalAlignment = .fill
btn.contentMode = .center
btn.imageView?.contentMode = .scaleAspectFit
I try this in swift 2.1, I adapt this code from Antoine answer. This may not good code but it solve my problem for now. You should make it better for you self.
import UIKit
class CustomUIButton: UIButton {
override func layoutSubviews() {
if var titleFrame : CGRect = titleLabel?.frame{
titleFrame.size = self.bounds.size
titleFrame.origin = CGPointZero
self.titleLabel!.frame = titleFrame
self.titleLabel!.textAlignment = .Center
}
}
}
There is this (sad) solution: https://stackoverflow.com/a/10200908/352628
I have a similar problem. It seems that the titleLabel is just very uncontrollable, and to get control you need to inject a UILabel subview to the button... That makes me sad :(

How do I prevent a button's background image from stretching?

I'm allocating a UIButtonTypeCustom to a UIView with a background image that is smaller than the button's frame.
Reason why the image is smaller is because I'm trying to add more of a "target area" for the UIButton. However, the image is being scaled to the full size of the frame, rather than just being the image's size.
I have tried setting the UIButton and UIButton's imageView's contentMode property to UIViewContentModeScaleAspectFit, but no luck, the image still gets stretched out.
Is there a way to do what I'm trying to do programmatically?
Thanks in advance!
A lot of people make the same mistake you do in regards to button images and then jump through hoops trying to make the button behave as they expect it to. Let's clear this up once and for all:
A UIButton has two types of images it can display -- a foreground image and a background image. The background image for a button is expected to replace the button's background texture. As such, it makes sense that it stretches to fill the entire background. However, the button's foreground image is expected to be an icon that may or may not display alongside text; it will not stretch. It may shrink if the frame is smaller than the image, but it will not stretch. You can even set the alignment of the foreground image using the Control alignment properties in Interface Builder.
A button's foreground and background image can be set in code like this:
// stretchy
[self setBackgroundImage:backgroundImage forState:UIControlStateNormal];
// not stretchy
[self setImage:forgroundImage forState:UIControlStateNormal];
You don't have access to the background imageView, but there is fully working workaround:
EDIT: There is an even better workaround then what I posted originally.
You can create a UIImage from any color, and call -setBackgroundImage:forState.
See bradley's answer, here:
https://stackoverflow.com/a/20303841/1147286
Original answer:
Instead of calling -setBackgroundImage:forState:, create a new UIImageView and add it as a subview of the button.
UIImageView *bgImageView = [[UIImageView alloc] initWithImage:img];
bgImageView.contentMode = UIViewContentModeScaleAspectFit;
[bgImageView setFrame:CGRectMake(0, 0, videoButton.frame.size.width, videoButton.frame.size.height)];
bgImageView.tag = 99;
[yourButton addSubview:bgImageView];
[yourButton bringSubviewToFront:yourButton.imageView];
Create the imageview
Set the content mode and frame
I also set a recognizable tag, so that when the screen rotates I can easily find my custom imageView in the button's subviews and reset its frame
Add it as a subview to the button
Bring the frontal imageView of the button to the front so our custom imageView doesn't overlap it
When the button needs to rotate just find the imageView by its tag and reset its frame:
UIImageView *bgImageView = (UIImageView *)[button viewWithTag:99];
[bgImageView setFrame:CGRectMake(0, 0, newWidth, newHeight)];
The cleanest and easiest way it probably to use the title insets of the button.
You set your image as the button image, and then you change the left title inset to match minus the width of your image:
myButton.titleEdgeInsets = UIEdgeInsetsMake(0, -myImage.width, 0, 0)
This will move the text back where it was before the image was added to its left. You can also use this value to add some padding to you button.
Stumbled on this problem too.
Adding image programmatically, as memmons thoroughly explained, did not help:(
I had a button 100x40 and image 100x100, it would appear squeezed, not fitted, as one would infer from "Aspect Fit" option. Actually, non of those view options had an effect.
I just had to rescale it so it would fit on a button, then use setImage:
UIImage *img=[UIImage imageNamed:#"myimage.png"];
CGImageRef imgRef = [img CGImage];
CGFloat imgW = CGImageGetWidth(imgRef);
CGFloat imgH = CGImageGetHeight(imgRef);
CGFloat btnW = myBttn.frame.size.width;
CGFloat btnH = myBttn.frame.size.height;
//get lesser button dimension
CGFloat minBtn=btnW;
if (btnW>btnH) {
minBtn=btnH;
}
//calculate scale using greater image dimension
CGFloat scl=imgH/minBtn;
if (imgW>imgH) {
scl=imgW/minBtn;
}
//scale image
UIImage *scaledImage = [UIImage imageWithCGImage:[img CGImage] scale:(img.scale * scl) orientation:(img.imageOrientation)];
//clean up
UIGraphicsEndImageContext();
//set it on a button
[myBttn setImage:scaledImage forState:UIControlStateNormal];
It is simple as:
ImageBtn.imageView?.contentMode = .scaleAspectFit
ImageBtn.setImage(chosenImage, for: .normal)
Another consideration is the BaseLine constraint. If your buttons have this constraint set (depicted as a horizontal or vertical line through multiple controls on your layout), it will cause your images to stretch without stretching the underlying button control. If your button is otherwise properly constrained (leading/trailing and top/bottom spaces, and etc...) removing the BaseLine constraint should have no impact on the layout, while allowing the foreground image to scale properly to the underlying button shape.
Answerbot answers the question with what is proper and correct to do. Don't fight the OS and use things as intended is always good advice. However, sometimes you need to break the rules.
I was able to mask the enlarged background image (not prevent it) by overlaying it with a black CAlayer then overlaying again with a properly resized image CAlayer. This was all done by creating a subclass of UIButton and overwriting the setHighlighted method.
NEED CODE?
- (void)setHighlighted:(BOOL)highlighted
{
super.highlighted = highlighted;
//
//Whenever an image needs to be highlighted, create a dimmed new image that is correctly sized. Below it is a englarged stretched image.
//
if (highlighted != _previousHighlightedSate)
{
_previousHighlightedSate = highlighted;
if (highlighted)
{
//Create a black layer so image can dim
_blackLayer = [CALayer layer];
_blackLayer.bounds = self.bounds;
CGRect rect = _blackLayer.bounds;
rect.size.width = rect.size.width*2;
rect.size.height = rect.size.height*2;
_blackLayer.bounds = rect;
_blackLayer.backgroundColor = [[UIColor blackColor] CGColor];
//create image layer
_nonStretchImageLayer = [CALayer layer];
_nonStretchImageLayer.backgroundColor = [UIColor blackColor].CGColor;
_nonStretchImageLayer.bounds = CGRectMake(0 , 0, self.bounds.size.width, self.bounds.size.height);
_nonStretchImageLayer.frame = CGRectMake(0 , 0, self.bounds.size.width, self.bounds.size.height);
_nonStretchImageLayer.contentsGravity = kCAGravityResizeAspect;//default is to resize
_nonStretchImageLayer.contents = (id)self.imageView.image.CGImage;
_nonStretchImageLayer.opacity = 0.5;
//add layers to image view
[self.imageView.layer addSublayer:_blackLayer];
[self.imageView.layer addSublayer:_nonStretchImageLayer];
}
else
{
//remove from image view
[_blackLayer removeFromSuperlayer];
[_nonStretchImageLayer removeFromSuperlayer];
//nil them out.
_blackLayer = nil;
_nonStretchImageLayer = nil;
}
}
Inspiration for this work around came from here
I guess the easiest solution is to use UIImage's resizableImageWithCapInsets method. Use UIEdgeInsetsMake to configure the free spaces.
might help someone
button.subviews.first?.contentMode = .scaleAspectFit
Swift version of Zoltán Matók answer
Just a copy of my code using SnapKit to do auto layout and syntatic sugar Then library for initilizations, it should work similar for normal Apples way of programatic layout.
let backButton = UIButton(type: .custom).then { (button) in
let image = UIImage(named: "backButtonIcon")?.withRenderingMode(.alwaysOriginal)
let imageView = UIImageView(image: image)
button.addSubview(imageView)
imageView.snp.makeConstraints { (make) in
make.center.equalTo(button.snp.center)
}
button.bringSubviewToFront(imageView)
button.contentMode = .scaleAspectFit
button.backgroundColor = .clear
button.isUserInteractionEnabled = true
button.isEnabled = true
button.imageView?.contentMode = .scaleAspectFit
button.imageView?.snp.makeConstraints({ (make) in
make.height.width.equalTo(24)
})
button.snp.makeConstraints { (make) in
make.height.width.equalTo(24)
}
}
You can use uibutton.imageView.contentMode for no stretching:
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
button.frame = CGRectMake(posX, posY, widthButton, heightButton);
[button setTitle:#"" forState:UIControlStateNormal];
[button setImage:[UIImage imageNamed:#"imageNamed"] forState:UIControlStateNormal];
[button setImage:[UIImage imageNamed:#"imageNamedHighlighted"] forState:UIControlStateHighlighted];
button.imageView.contentMode = UIViewContentModeScaleAspectFit;
[button addTarget:self action:#selector(functionMenu:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview: button];
What you need to do is add your image as a UIImageView.
Than add a button with transperent background (UIColor ClearColor) on top of it with your desired width and height.

Resources