Give inset to UIImageView before setting Its frame - ios

I have an UITextField component which has an icon on the right side of it. Icon is just an UIImageView. I'm trying to give inset to UIImageView with below code
imageView.image = UIImage(named: "example")?.withAlignmentRectInsets(UIEdgeInsets(top: -4, left: 0, bottom: -4, right: 0))
However, It doesn't work cuz It's frame hasn't been set when setting Its' Image. I'm giving Its frame with below code;
iconImageView.frame = CGRect(
x: bounds.size.width - iconWidth - iconMarginLeft,
y: bounds.size.height - textHeight() - iconMarginBottom,
width: iconWidth,
height: textHeight()
)
and how I setup UIImageView
fileprivate func createIconImageView() {
let iconImageView = UIImageView()
iconImageView.backgroundColor = .clear
iconImageView.contentMode = .scaleAspectFill
iconImageView.autoresizingMask = [.flexibleTopMargin, .flexibleRightMargin]
if (hasToolTip) {
let tapGesture = UITapGestureRecognizer(target: self, action:#selector(toolTipTapped(_:)))
iconImageView.addGestureRecognizer(tapGesture)
iconImageView.isUserInteractionEnabled = true
let image = UIImage(named: "infotooltip")
image?.accessibilityIdentifier = "tooltipImage"
iconImageView.image = image!
changeIconAlphaToOne()
self.iconImageView = iconImageView
} else {
self.iconImageView = iconImageView
changeIconAlphaToZero()
}
addSubview(iconImageView)
}
My problem is that, I need to give UIEdgeInset to the image. However, because I'm trying to give it before setting the frame, It doesn't work. How can I achieve this?
I also try to resize the image by referencing below post but doesn't work for me. I also DO NOT want to put it inside a content view which will make my component class more complicated.
The simplest way to resize an UIImage?

Related

How to resize UIImage ratio into view in ios swift?

I am trying to resize uiimage ratio. Right now i am getting image into square not in correct aspect ratio. If i change the width and height uiimage into pickImage.frame.size.width, pickImage.frame.size.hight then UIImage look so large.
If i set pickImage?.contentMode = .scaleAspectFit then image set its position but drop shadow is shown full image view not image picked one.
Here is the screenshots of result i got
And close button should be top left corner, here when i pick image from image picker any other position of close button image set to properly based on landscape or portrait.
Here is the code i used:
func addImage(url : URL) {
let tag = Int(arc4random_uniform(6))
pickImage = UIImageView()
pickImage?.sd_setImage(with:url)
pickImage?.sd_setShowActivityIndicatorView(true)
pickImage?.backgroundColor = UIColor.lightGray
pickImage?.sd_setIndicatorStyle(.gray)
pickImage?.frame = CGRect(x: randomNumber(inRange:
200...Int(touchDrawview.frame.width - 200)), y: Int(getYValue(maxYValue:
Int(touchDrawview.frame.height - 200))), width: 200, height: 200)
pickImage?.autoresizingMask = [.flexibleTopMargin, .flexibleHeight,
.flexibleRightMargin, .flexibleLeftMargin, .flexibleTopMargin,
.flexibleWidth]
pickImage?.contentMode = .scaleAspectFit
pickImage?.tag = tag
pickImage?.isUserInteractionEnabled = true
let imageclose = UIImage(named: "imageclose")
closeImage = UIImageView(image : imageclose)
closeImage?.frame = CGRect(x: 10, y: 10, width: 30, height: 30)
closeImage?.tag = tag
closeImage?.isHidden = true
closeImage?.isUserInteractionEnabled = true
pickImage?.layer.shadowColor = UIColor.white.cgColor
pickImage?.layer.shadowOffset = CGSize(width: 0, height: 3)
pickImage?.layer.shadowOpacity = 1
pickImage?.layer.shadowRadius = 1.0
pickImage?.clipsToBounds = false
let longGuetureImage = UILongPressGestureRecognizer(target: self, action:
#selector(longPressImage(sender:)))
longGuetureImage.minimumPressDuration = 0.1
pickImage?.isUserInteractionEnabled = true
longGuetureImage.delegate = self
pickImage?.addGestureRecognizer(longGuetureImage)
let panGesture = UIPanGestureRecognizer(target: self, action:
#selector(handlePanImage(recognizer:)))
panGesture.delegate = self
pickImage?.isUserInteractionEnabled = true
pickImage?.addGestureRecognizer(panGesture)
let tapGuetureImage = UITapGestureRecognizer(target: self, action:
#selector(removeImage(sender:)))
tapGuetureImage.delegate = self
closeImage?.addGestureRecognizer(tapGuetureImage)
let tapGueturemainImage = UITapGestureRecognizer(target: self, action:
#selector(selectdragImageTap(_:)))
tapGueturemainImage.delegate = self
pickImage?.addGestureRecognizer(tapGueturemainImage)
let rotate = UIRotationGestureRecognizer(target: self, action:
#selector(handlerotateImage(recognizer:)))
rotate.delegate = self
pickImage?.addGestureRecognizer(rotate)
let pinch = UIPinchGestureRecognizer(target: self, action:
#selector(handlePinchImage(sender:)))
pinch.delegate = self
pickImage?.addGestureRecognizer(pinch)
pickImage?.dropShadowOff()
addPickedImage(image: pickImage!, closeimage: closeImage!,imageType :
PickedType.image.rawValue,imageData: url.absoluteString)
pickImage = nil
closeImage = nil
}
Try This:
pickImage?.contentMode = .scaleAspectFill
pickImage?.clipsToBounds = true
Create a UIView with clipsToBounds = true first, apply shadow on this view and then add your pickimage and button as a subView in this view. because clipsToBounds = true stop dropping shadow on current view.
When the image is resized, the aspect ratio of image may not be the same as the view. There are two approaches for what you are trying to achieve.
Approach 1:
Resize the image to fit the view. Here the aspect ratio may be different than view hence image may get distorted. To resize image, refer below,
Refer:
https://aurvan.github.io/atkit-ios-release/index.html
Class Reference:
https://aurvan.github.io/atkit-ios-release/helpbook/Extensions/UIImage.html
Code:
import ATKit
let anImage :UIImage = UIImage(named: "DefaultAvatar")!
let aResizedImage :UIImage? = anImage.resize(size: CGSize(width: 100.0, height: 200.0), scaleMode: UIImageScaleMode.aspectFit)
Approach 2: Calculate the image size manually and adjust the close button from the horizontal center of the view. I have not tried the code, but something like below should work,
anImageX = (anImageViewWidth - anImageWidth) / 2.0
anImageY = (anImageViewHeight - anImageHeight) / 2.0

iOS swift how to place an imageview in a uiview exactly

I have an issue, I'm creating an imageView programmatically and then add it to a center view, which is kind of working. But the problem is that is not taking the whole space in the center view, it appears yes in the uiview but not covering all always a bit down. Any help?
The code:
//let backgroundImage = UIImageView(frame: centerView.frame)
let backgroundImage: UIImageView = UIImageView(frame: CGRect(x: 0, y: 0, width: self.centerView.bounds.size.width, height: self.centerView.bounds.size.height))
print("backgorundImage coordinates: \(backgroundImage.frame)")
backgroundImage.image = drawOverImage
backgroundImage.sizeThatFits(CGSizeMake(centerView.bounds.width, self.centerView.bounds.height))
//check this the image is being drawn bottom because is the fame for the previous 0.0
//backgroundImage.autoPinEdgeToSuperviewMargin(ALEdge.Top, relation: NSLayoutRelation.Equal)
//backgroundImage.contentMode = UIViewContentMode.ScaleAspectFill //too big
//backgroundImage.contentMode = UIViewContentMode.ScaleAspectFit //sama
backgroundImage.contentMode = UIViewContentMode.ScaleAspectFill
backgroundImage.clipsToBounds = true
//imageView.image = background
backgroundImage.center = view.center
let coordinatesForImage: CGRect = self.view.convertRect(backgroundImage.frame, toView: centerView)
let pointOfImage: CGPoint = backgroundImage.convertPoint(self.centerView.frame.origin, toView: backgroundImage)
print("coordinates test: \(coordinatesForImage)")
print("point x: \(pointOfImage.x)")
print("point y: \(pointOfImage.y)")
//backgroundImage.contentMode = UIViewContentMode.ScaleToFill
self.centerView.insertSubview(backgroundImage, atIndex: 0)
let pointOfImageToSuperView: CGPoint = (backgroundImage.superview?.convertPoint(backgroundImage.center, toView: self.centerView))!
print("superview imagepoint: \(pointOfImageToSuperView)")
The comments are all the thing I'm trying to do.
EDIT:
This is what is happening.
I missing a little bit from the bottom, now I don't know if is the size of the image or what, could i change the size of the uiview to match the image?
Simply try:
let backgroundImage: UIImageView = UIImageView(frame: self.centerView.bounds)
backgroundImage.clipsToBounds = true
backgroundImage.contentMode = .ScaleAspectFill
self.centerView.addSubview(backgroundImage)

How to center an image in navigationBar across all UIViewControllers? Swift / Obj-C

Problem visually:
I have tried putting the image in the center of its own frame with no luck. I have also tried to center it with playing the x of the CGRect with no luck either. I presume I can just put an empty icon with the same background as the navigation bar; however, I don't want to do it that way. I might have 2-3 icons on the right; then what?
let image = UIImage(named: "some_logo")!
let imageSize = CGSizeMake(60, 42)
let marginX: CGFloat = (self.navigationController!.navigationBar.frame.size.width / 2) - (imageSize.width / 2)
let imageView = UIImageView(frame: CGRect(x: marginX, y: 0, width: imageSize.width, height: imageSize.height))
imageView.image = image
imageView.contentMode = .ScaleAspectFit
self.navigationItem.titleView = imageView
I prefer swift but obj-c solutions are welcomed as well.
Any pointers appreciated.
This app has nothing to do with KIA, it is just some logo I got off the google search, searching "some logo".
I have faced the same issue. Then i tried one code shown below.
override func viewDidAppear(animated: Bool) {
let imageView = UIImageView(frame: CGRect(x: 0, y: 0, width: 150, height: 40))
imageView.contentMode = .ScaleAspectFit
let image = UIImage(named: "googlePlus")
imageView.image = image
navigationItem.titleView = imageView
}
This Code working fine when i tested with Left & Right Bar Button.
But in my previous code there is no Right Bar Button.
So the image is moving towards right.
For solving this i created a Right Bar Button & change the Tint color to clear color.
So everything seems to be working fine. This is one Temporary Solution for your problem.
The easiest way of doing this is in Interface Builder.
Simply drag a 'NavigationItem' from the object library and place it into your ViewController, then place a UIView where the title goes (ensure you set the background to 'clear')
Then place a UIImageView into that view and set the image in the Attributes Inspector to your required image. Scale your UIImage accordingly and set your your constraints accordingly.
I created an extension for solving this problem using the hint of #idrougge.
In order to center the title view image no matter what buttons you have, a content view is set as title view, then the image view is added as child of the content view. Finally, using constraints the image view is aligned inside its parent (content view).
import UIKit
extension UIViewController {
func addLogoToNavigationBarItem() {
let imageView = UIImageView()
imageView.translatesAutoresizingMaskIntoConstraints = false
imageView.heightAnchor.constraint(equalToConstant: <your_height>).isActive = true
imageView.contentMode = .scaleAspectFit
imageView.image = <your_image>
//imageView.backgroundColor = .lightGray
// In order to center the title view image no matter what buttons there are, do not set the
// image view as title view, because it doesn't work. If there is only one button, the image
// will not be aligned. Instead, a content view is set as title view, then the image view is
// added as child of the content view. Finally, using constraints the image view is aligned
// inside its parent.
let contentView = UIView()
self.navigationItem.titleView = contentView
self.navigationItem.titleView?.addSubview(imageView)
imageView.centerXAnchor.constraint(equalTo: contentView.centerXAnchor).isActive = true
imageView.centerYAnchor.constraint(equalTo: contentView.centerYAnchor).isActive = true
}
}
I hope this helps someone,
Xavi
As question heading stated "Swift / Obj-C" so I am sharing code of Obj-C :
UIImageView *titleImage = (UIImageView *)self.navigationItem.titleView;
titleImage = [[UIImageView alloc]initWithFrame:CGRectMake((self.navigationController.navigationBar.frame.size.width/2) - (100/2), 0, 100,self.navigationController.navigationBar.frame.size.height)];
//setting the image for UIImageView
titleImage.image = [UIImage imageNamed:#"someLogo"];
titleImage.contentMode = UIViewContentModeCenter;
self.navigationItem.titleView = titleImage;
Had same issue on phones with smaller sizes. Image in title was moving to right. Causing this issue back button -> [back_button][title_view]. Its centered when there is no back button or there is right bar button. Richard Hope's was right, you just need to put UIView first, and then put UIImageView as subview. Programmatically could be done like this.
private var imageView: UIView {
let bannerWidth = navigationBar.frame.size.width * 0.5 // 0.5 its multiplier to get correct image width
let bannerHeight = navigationBar.frame.size.height
let view = UIView()
view.backgroundColor = .clear
view.frame = CGRect(x: 0, y: 0, width: bannerWidth, height: bannerHeight)
let image = UIImage(named: "your_image_name")
let imageView = UIImageView(image: image)
imageView.contentMode = .scaleAspectFit
imageView.frame = CGRect(x: 0, y: 0, width: view.frame.width, height: view.frame.height)
view.addSubview(imageView)
return view
}
The just change titleView
navigationItem.titleView = imageView
What about setting the center of your image equals to the navigationBar.center instead of setting a margin?
//assuming we already have our navigationController
let myNicelLogoWidth = 100
let myNiceLogoHeight = 50
//start positioning your logo at 0.0, 0.0
let imageView = UIImageView(frame: CGRect(x: 0, y: 0, width: myNicelLogoWidth, height: myNiceLogoHeight))
imageView.contentMode = .scaleAspectFit
imageView.center = navigationBar.center //the put your image at the center
let image = UIImage(named: "myNiceLogoImage")
imageView.image = image
navigationItem.titleView = imageView
I once face with this problem, and finally i found out that the problem is the previous navigation bar title still located next to burger button, but it's invisible.
Fast solution but not sure if it's the best is to change the previous navigation bar title to empty string before show the next view controller.
Hope it's help.

Image in top background of UITableView - iOS

I can set an image to my TableView background, but the image is in the center of the view.
How can I set the image to top ?
I'm using staticTableView
let image = UIImageView(image: UIImage(named: "img.jpg"))
self.settingsTableView.backgroundView = image
self.settingsTableView.backgroundView?.frame = CGRectZero
self.settingsTableView.backgroundView?.contentMode = UIViewContentMode.ScaleAspectFit
If you're using a static table and theres no chance of changing it you might want to take an approach like this:
override func viewDidLoad() {
super.viewDidLoad()
//Create the UIImage
let image = UIImage(named: "testing")
//Create a container view that will take all of the tableView space and contain the imageView on top
let containerView = UIView(frame: CGRect(x: 0.0, y: 0.0, width: self.view.bounds.width, height: self.view.bounds.height))
//Create the UIImageView that will be on top of our table
let imageView = UIImageView(frame: CGRect(x: 0.0, y: 0.0, width: self.view.bounds.width, height: image!.size.height))
//Set the image
imageView.image = image
//Clips to bounds so the image doesnt go over the image size
imageView.clipsToBounds = true
//Scale aspect fill so the image doesn't break the aspect ratio to fill in the header (it will zoom)
imageView.contentMode = UIViewContentMode.ScaleAspectFit
containerView.addSubview(imageView)
self.tableView.backgroundView = containerView
}
Make the cells or the headers transparent as you wish. I don't know how your UI should work. This method WON'T scroll the imageView but you can simply do it in the scrollView delegate method. Let me know if you need it to scroll and I'll help you out

How do I put the image on the right side of the text in a UIButton?

I don't want to use a subview if I can avoid it. I want a UIButton with a background image, text, and an image in it. Right now, when I do that, the image is on the left side of the text. The background image, text, and image all have different highlight states.
Simplest solution:
iOS 10 & up, Swift:
button.transform = CGAffineTransform(scaleX: -1.0, y: 1.0)
button.titleLabel?.transform = CGAffineTransform(scaleX: -1.0, y: 1.0)
button.imageView?.transform = CGAffineTransform(scaleX: -1.0, y: 1.0)
Before iOS 10, Swift/Obj-C:
button.transform = CGAffineTransformMakeScale(-1.0, 1.0);
button.titleLabel.transform = CGAffineTransformMakeScale(-1.0, 1.0);
button.imageView.transform = CGAffineTransformMakeScale(-1.0, 1.0);
iOS 9 & up, Swift: (Recommended)
button.semanticContentAttribute = .forceRightToLeft
Despite some of the suggested answers being very creative and extremely clever, the simplest solution is as follows:
button.semanticContentAttribute = UIApplication.shared
.userInterfaceLayoutDirection == .rightToLeft ? .forceLeftToRight : .forceRightToLeft
As simple as that. As a bonus, the image will be at the left side in right-to-left locales.
EDIT: as the question has been asked a few times, this is iOS 9 +.
UPDATED FOR XCODE 9 (Via Interface Builder)
There's an easier way from the Interface Builder.
Select the UIButton and select this option in the View Utilities > Semantic:
That's it! Nice and simple!
OPTIONAL - 2nd step:
If you want to adjust the spacing between the image and the title you can change the Image Inset here:
Subclassing UIButton is completely unnecessary. Instead you can simply set a high left inset value for the image insets, and a small right inset for the title. Something like this:
button.imageEdgeInsets = UIEdgeInsetsMake(0., button.frame.size.width - (image.size.width + 15.), 0., 0.);
button.titleEdgeInsets = UIEdgeInsetsMake(0., 0., 0., image.size.width);
I'm giving Inspire48 the credit for this one. Based on his suggestion and looking at that other question I came up with this. Subclass UIButton and override these methods.
#implementation UIButtonSubclass
- (CGRect)imageRectForContentRect:(CGRect)contentRect
{
CGRect frame = [super imageRectForContentRect:contentRect];
frame.origin.x = CGRectGetMaxX(contentRect) - CGRectGetWidth(frame) - self.imageEdgeInsets.right + self.imageEdgeInsets.left;
return frame;
}
- (CGRect)titleRectForContentRect:(CGRect)contentRect
{
CGRect frame = [super titleRectForContentRect:contentRect];
frame.origin.x = CGRectGetMinX(frame) - CGRectGetWidth([self imageRectForContentRect:contentRect]);
return frame;
}
#end
Just update the insets when the title is changed. You need to compensate for the inset with an equal and opposite inset on the other side.
[thebutton setTitle:title forState:UIControlStateNormal];
thebutton.titleEdgeInsets = UIEdgeInsetsMake(0, -thebutton.imageView.frame.size.width, 0, thebutton.imageView.frame.size.width);
thebutton.imageEdgeInsets = UIEdgeInsetsMake(0, thebutton.titleLabel.frame.size.width, 0, -thebutton.titleLabel.frame.size.width);
All of these answers, as of January 2016, are unnecessary. In Interface Builder, set the View Semantic to Force Right-to-Left, or if you prefer programmatic way, semanticContentAttribute = .forceRightToLeft That will cause the image to appear on the right of your text.
In interface builder you can configure options Edge Insets for UIButton, separately each of three parts: content, image, title
Xcode 8:
I decided not to use the standard button image view because the proposed solutions to move it around felt hacky. This got me the desired aesthetic, and it is intuitive to reposition the button by changing the constraints:
extension UIButton {
func addRightIcon(image: UIImage) {
let imageView = UIImageView(image: image)
imageView.translatesAutoresizingMaskIntoConstraints = false
addSubview(imageView)
let length = CGFloat(15)
titleEdgeInsets.right += length
NSLayoutConstraint.activate([
imageView.leadingAnchor.constraint(equalTo: self.titleLabel!.trailingAnchor, constant: 10),
imageView.centerYAnchor.constraint(equalTo: self.titleLabel!.centerYAnchor, constant: 0),
imageView.widthAnchor.constraint(equalToConstant: length),
imageView.heightAnchor.constraint(equalToConstant: length)
])
}
}
Update: Swift 3
class ButtonIconRight: UIButton {
override func imageRect(forContentRect contentRect:CGRect) -> CGRect {
var imageFrame = super.imageRect(forContentRect: contentRect)
imageFrame.origin.x = super.titleRect(forContentRect: contentRect).maxX - imageFrame.width
return imageFrame
}
override func titleRect(forContentRect contentRect:CGRect) -> CGRect {
var titleFrame = super.titleRect(forContentRect: contentRect)
if (self.currentImage != nil) {
titleFrame.origin.x = super.imageRect(forContentRect: contentRect).minX
}
return titleFrame
}
}
Original answer for Swift 2:
A solution that handles all horizontal alignments, with a Swift implementation example. Just translate to Objective-C if needed.
class ButtonIconRight: UIButton {
override func imageRectForContentRect(contentRect:CGRect) -> CGRect {
var imageFrame = super.imageRectForContentRect(contentRect)
imageFrame.origin.x = CGRectGetMaxX(super.titleRectForContentRect(contentRect)) - CGRectGetWidth(imageFrame)
return imageFrame
}
override func titleRectForContentRect(contentRect:CGRect) -> CGRect {
var titleFrame = super.titleRectForContentRect(contentRect)
if (self.currentImage != nil) {
titleFrame.origin.x = CGRectGetMinX(super.imageRectForContentRect(contentRect))
}
return titleFrame
}
}
Also worth noting that it handles quite well image & title insets.
Inspired from jasongregori answer ;)
If this need to be done in UIBarButtonItem, additional wrapping in view should be used
This will work
let view = UIView()
let button = UIButton()
button.setTitle("Skip", for: .normal)
button.setImage(#imageLiteral(resourceName:"forward_button"), for: .normal)
button.semanticContentAttribute = .forceRightToLeft
button.sizeToFit()
view.addSubview(button)
view.frame = button.bounds
navigationItem.rightBarButtonItem = UIBarButtonItem(customView: view)
This won't work
let button = UIButton()
button.setTitle("Skip", for: .normal)
button.setImage(#imageLiteral(resourceName:"forward_button"), for: .normal)
button.semanticContentAttribute = .forceRightToLeft
button.sizeToFit()
navigationItem.rightBarButtonItem = UIBarButtonItem(customView: button)
Do Yourself. Xcode10, swift4,
For programmatically UI design
lazy var buttonFilter : ButtonRightImageLeftTitle = {
var button = ButtonRightImageLeftTitle()
button.setTitle("Playfir", for: UIControl.State.normal)
button.setImage(UIImage(named: "filter"), for: UIControl.State.normal)
button.backgroundColor = UIColor.red
button.contentHorizontalAlignment = .left
button.titleLabel?.font = UIFont.systemFont(ofSize: 16)
return button
}()
Edge inset values are applied to a rectangle to shrink or expand the
area represented by that rectangle. Typically, edge insets are used
during view layout to modify the view’s frame. Positive values cause
the frame to be inset (or shrunk) by the specified amount. Negative
values cause the frame to be outset (or expanded) by the specified
amount.
class ButtonRightImageLeftTitle: UIButton {
override func layoutSubviews() {
super.layoutSubviews()
guard imageView != nil else { return }
imageEdgeInsets = UIEdgeInsets(top: 5, left: (bounds.width - 35), bottom: 5, right: 5)
titleEdgeInsets = UIEdgeInsets(top: 0, left: -((imageView?.bounds.width)! + 10), bottom: 0, right: 0 )
}
}
for StoryBoard UI design
iOS 15 brought an update where you can now handle image placements in buttons in a simpler non messier way, ie. without insets.
In XIB/Storyboards:
Simply set the button 'placement' property to leading/training/top/bottom after adding an image property to button. Since it's leading/training, there is an added advantage of it supporting RTL
**In code (Programmatically): **
Use Button Configuration property programmatically
This is not a backward compatible feature, and will work only in iOS15+ as was demonstrated in WWDC '21 - https://developer.apple.com/videos/play/wwdc2021/10064/?time=236
Developer documentation: https://developer.apple.com/documentation/uikit/uibutton/configuration?changes=_4
Here is solution for UIButton with center aligned content.
This code make image right aligned and allows to use imageEdgeInsets and titleEdgeInsets for precious positioning.
Subclass UIButton with your custom class and add:
- (CGRect)imageRectForContentRect:(CGRect)contentRect {
CGRect frame = [super imageRectForContentRect:contentRect];
CGFloat imageWidth = frame.size.width;
CGRect titleRect = CGRectZero;
titleRect.size = [[self titleForState:self.state] sizeWithAttributes:#{NSFontAttributeName: self.titleLabel.font}];
titleRect.origin.x = (self.frame.size.width - (titleRect.size.width + imageWidth)) / 2.0 + self.titleEdgeInsets.left - self.titleEdgeInsets.right;
frame.origin.x = titleRect.origin.x + titleRect.size.width - self.imageEdgeInsets.right + self.imageEdgeInsets.left;
return frame;
}
- (CGRect)titleRectForContentRect:(CGRect)contentRect {
CGFloat imageWidth = [self imageForState:self.state].size.width;
CGRect frame = [super titleRectForContentRect:contentRect];
frame.origin.x = (self.frame.size.width - (frame.size.width + imageWidth)) / 2.0 + self.titleEdgeInsets.left - self.titleEdgeInsets.right;
return frame;
}
Extension Way
Using extension to set image on the right side with custom offset
extension UIButton {
func addRightImage(image: UIImage, offset: CGFloat) {
self.setImage(image, for: .normal)
self.imageView?.translatesAutoresizingMaskIntoConstraints = false
self.imageView?.centerYAnchor.constraint(equalTo: self.centerYAnchor, constant: 0.0).isActive = true
self.imageView?.trailingAnchor.constraint(equalTo: self.trailingAnchor, constant: -offset).isActive = true
}
}
Being that the transform solution doesn't work in iOS 11 I decided to write a new approach.
Adjusting the buttons semanticContentAttribute gives us the image nicely to the right without having to relayout if the text changes. Because of this it's the ideal solution. However I still need RTL support. The fact that an app can not change it's layout direction in the same session resolves this issue easily.
With that said, it's pretty straight forward.
extension UIButton {
func alignImageRight() {
if UIApplication.shared.userInterfaceLayoutDirection == .leftToRight {
semanticContentAttribute = .forceRightToLeft
}
else {
semanticContentAttribute = .forceLeftToRight
}
}
}
Swift -Extend the UiButton and put these lines
if let imageWidth = self.imageView?.frame.width {
self.titleEdgeInsets = UIEdgeInsetsMake(0, -imageWidth, 0, imageWidth);
}
if let titleWidth = self.titleLabel?.frame.width {
let spacing = titleWidth + 20
self.imageEdgeInsets = UIEdgeInsetsMake(0, spacing, 0, -spacing);
}
Building on Piotr Tomasik's elegant solution: if you want to have a bit of spacing between the button label and image as well, then include that in your edge insets as follows (copying my code here that works perfectly for me):
CGFloat spacing = 3;
CGFloat insetAmount = 0.5 * spacing;
// First set overall size of the button:
button.contentEdgeInsets = UIEdgeInsetsMake(0, insetAmount, 0, insetAmount);
[button sizeToFit];
// Then adjust title and image insets so image is flipped to the right and there is spacing between title and image:
button.titleEdgeInsets = UIEdgeInsetsMake(0, -button.imageView.frame.size.width - insetAmount, 0, button.imageView.frame.size.width + insetAmount);
button.imageEdgeInsets = UIEdgeInsetsMake(0, button.titleLabel.frame.size.width + insetAmount, 0, -button.titleLabel.frame.size.width - insetAmount);
Thanks Piotr for your solution!
Erik
Took #Piotr's answer and made it into a Swift extension. Make sure to set the image and title before calling this, so that the button sizes properly.
extension UIButton {
/// Makes the ``imageView`` appear just to the right of the ``titleLabel``.
func alignImageRight() {
if let titleLabel = self.titleLabel, imageView = self.imageView {
// Force the label and image to resize.
titleLabel.sizeToFit()
imageView.sizeToFit()
imageView.contentMode = .ScaleAspectFit
// Set the insets so that the title appears to the left and the image appears to the right.
// Make the image appear slightly off the top/bottom edges of the button.
self.titleEdgeInsets = UIEdgeInsets(top: 0, left: -1 * imageView.frame.size.width,
bottom: 0, right: imageView.frame.size.width)
self.imageEdgeInsets = UIEdgeInsets(top: 4, left: titleLabel.frame.size.width,
bottom: 4, right: -1 * titleLabel.frame.size.width)
}
}
}
With Xcode 13.3 I solved in the following few steps and as well adding padding to the image.
After creating the button then do this as listed below:
First define the image:
let symbol = UIImage(named: "put name of your symbol here")
Then in viewDidLoad where you created the button, initialise the above defined image in 1, to add the image to the button & set the properties:
button.setImage(symbol, for: .normal)
button.semanticContentAttribute = .forceRightToLeft
button.configuration?.imagePadding = 2
And don't forget to add your button to the view.
Subclassing and over-riding layoutSubviews is probably your best way to go.
Referenced from: iPhone UIButton - image position
A swift option that does what you want without playing with any insets:
class RightImageButton: UIButton {
override func layoutSubviews() {
super.layoutSubviews()
if let textSize = titleLabel?.intrinsicContentSize(),
imageSize = imageView?.intrinsicContentSize() {
let wholeWidth = textSize.width + K.textImageGap + imageSize.width
titleLabel?.frame = CGRect(
x: round(bounds.width/2 - wholeWidth/2),
y: 0,
width: ceil(textSize.width),
height: bounds.height)
imageView?.frame = CGRect(
x: round(bounds.width/2 + wholeWidth/2 - imageSize.width),
y: RoundRetina(bounds.height/2 - imageSize.height/2),
width: imageSize.width,
height: imageSize.height)
}
}
struct K {
static let textImageGap: CGFloat = 5
}
}
Solutions mentioned here stopped working, once I enabled Auto Layout. I had to come up with my own:
Subclass UIButton and override layoutSubviews method:
//
// MIThemeButtonImageAtRight.m
// Created by Lukasz Margielewski on 7/9/13.
//
#import "MIThemeButtonImageAtRight.h"
static CGRect CGRectByApplyingUIEdgeInsets(CGRect frame, UIEdgeInsets insets);
#implementation MIThemeButtonImageAtRight
- (void)layoutSubviews
{
[super layoutSubviews];
CGRect contentFrame = CGRectByApplyingUIEdgeInsets(self.bounds, self.contentEdgeInsets);
CGRect frameIcon = self.imageView.frame;
CGRect frameText = self.titleLabel.frame;
frameText.origin.x = CGRectGetMinX(contentFrame) + self.titleEdgeInsets.left;
frameIcon.origin.x = CGRectGetMaxX(contentFrame) - CGRectGetWidth(frameIcon);
self.imageView.frame = frameIcon;
self.titleLabel.frame = frameText;
}
#end
static CGRect CGRectByApplyingUIEdgeInsets(CGRect frame, UIEdgeInsets insets){
CGRect f = frame;
f.origin.x += insets.left;
f.size.width -= (insets.left + insets.right);
f.origin.y += (insets.top);
f.size.height -= (insets.top + insets.bottom);
return f;
}
Result:
swift 3.0 Migration
solution given by jasongregori
class ButtonIconRight: UIButton {
override func imageRect(forContentRect contentRect: CGRect) -> CGRect {
var imageFrame = super.imageRect(forContentRect: contentRect)
imageFrame.origin.x = super.titleRect(forContentRect: contentRect).maxX - imageFrame.width
return imageFrame
}
override func titleRect(forContentRect contentRect: CGRect) -> CGRect {
var titleFrame = super.titleRect(forContentRect: contentRect)
if (self.currentImage != nil) {
titleFrame.origin.x = super.imageRect(forContentRect: contentRect).minX
}
return titleFrame
}
Xcode 11.4 Swift 5.2
For anyone trying to mirror the Back button style with the chevron like this:
import UIKit
class NextBarButton: UIBarButtonItem {
convenience init(target: Any, selector: Selector) {
// Create UIButton
let button = UIButton(frame: .zero)
// Set Title
button.setTitle("Next", for: .normal)
button.setTitleColor(.systemBlue, for: .normal)
button.titleLabel?.font = UIFont.systemFont(ofSize: 17)
// Configure Symbol
let config = UIImage.SymbolConfiguration(pointSize: 19.0, weight: .semibold, scale: .large)
let image = UIImage(systemName: "chevron.right", withConfiguration: config)
button.setImage(image, for: .normal)
// Add Target
button.addTarget(target, action: selector, for: .touchUpInside)
// Put the Image on the right hand side of the button
// Credit to liau-jian-jie for this part
button.transform = CGAffineTransform(scaleX: -1.0, y: 1.0)
button.titleLabel?.transform = CGAffineTransform(scaleX: -1.0, y: 1.0)
button.imageView?.transform = CGAffineTransform(scaleX: -1.0, y: 1.0)
// Customise spacing to match system Back button
button.imageEdgeInsets = UIEdgeInsets(top: 0.0, left: -18.0, bottom: 0.0, right: 0.0)
button.titleEdgeInsets = UIEdgeInsets(top: 0.0, left: -12.0, bottom: 0.0, right: 0.0)
self.init(customView: button)
}
}
Implementation:
override func viewDidLoad() {
super.viewDidLoad()
let nextButton = NextBarButton(target: self, selector: #selector(nextTapped))
navigationItem.rightBarButtonItem = nextButton
}
#objc func nextTapped() {
// your code
}
Swift 3:
open override func imageRect(forContentRect contentRect: CGRect) -> CGRect {
var frame = super.imageRect(forContentRect: contentRect)
let imageWidth = frame.size.width
var titleRect = CGRect.zero
titleRect.size = self.title(for: self.state)!.size(attributes: [NSFontAttributeName: self.titleLabel!.font])
titleRect.origin.x = (self.frame.size.width - (titleRect.size.width + imageWidth)) / 2.0 + self.titleEdgeInsets.left - self.titleEdgeInsets.right;
frame.origin.x = titleRect.origin.x + titleRect.size.width - self.imageEdgeInsets.right + self.imageEdgeInsets.left;
return frame
}
open override func titleRect(forContentRect contentRect: CGRect) -> CGRect {
var frame = super.titleRect(forContentRect: contentRect)
if let imageWidth = self.image(for: self.state)?.size.width {
frame.origin.x = (self.frame.size.width - (frame.size.width + imageWidth)) / 2.0 + self.titleEdgeInsets.left - self.titleEdgeInsets.right;
}
return frame
}
How about Constraints? Unlike semanticContentAttribute, they don't change semantics. Something like this perhaps:
button.rightAnchorconstraint(equalTo: button.rightAnchor).isActive = true
or in Objective-C:
[button.imageView.rightAnchor constraintEqualToAnchor:button.rightAnchor].isActive = YES;
Caveats: Untested, iOS 9+
After trying multiple solutions from around the internet, I was not achieving the exact requirement. So I ended up writing custom utility code. Posting to help someone in future.
Tested on swift 4.2
// This function should be called in/after viewDidAppear to let view render
func addArrowImageToButton(button: UIButton, arrowImage:UIImage = #imageLiteral(resourceName: "my_image_name") ) {
let btnSize:CGFloat = 32
let imageView = UIImageView(image: arrowImage)
let btnFrame = button.frame
imageView.frame = CGRect(x: btnFrame.width-btnSize-8, y: btnFrame.height/2 - btnSize/2, width: btnSize, height: btnSize)
button.addSubview(imageView)
//Imageview on Top of View
button.bringSubviewToFront(imageView)
}
for this issue you can create UIView inside "label with UIImage view" and set UIView class as a UIControl and create IBAction as tuch up in side
Swift 4 & 5
Change the direction of UIButton image (RTL and LTR)
extension UIButton {
func changeDirection(){
isArabic ? (self.contentHorizontalAlignment = .right) : (self.contentHorizontalAlignment = .left)
// left-right margin
self.imageEdgeInsets = UIEdgeInsets(top: 0, left: 5, bottom: 0, right: 5)
self.titleEdgeInsets = UIEdgeInsets(top: 0, left: 5, bottom: 0, right: 5)
}
}

Resources