Modify UIImage renderingMode from a storyboard/xib file - ios

Is it possible to modify a UIImage's renderingMode from a storyboard or xib editor?
The goal is to apply tintColor to the particular UIImageView object.

You can set the image rendering mode not in the .xib file, but in an .xcassets library.
After adding an image to an asset library, select the image and open the attributes inspector on the right side of Xcode. Find the attribute 'Render As' and set it to 'template'.
After setting an image's rendering mode, you can add a tint color to the UIImageView in a .xib or .storyboard file to adjust the image color.
This sets the property on the image wherever it's used rather than just in one interface builder file, but in almost all cases (that I've encountered) this is the behavior you want.
A few things to note:
The image color will not appear to have changed in interface builder (as of Xcode 6.1.1) but will work when the application is run.
I've experienced some bugginess with this feature and in some situations I've had to remove and re-add the UIImageView. I have not looked into that deeply.
This also works great on other UIKitComponents such as images in UIButton's and UIBarButtonItem's.
If you have a bunch of white images that are invisible in your asset library, making them black/transparent images and changing the rendering mode will make your life up to 10x better.

Here's how you can do it in .xib or storyboard files:
(Obj-C) Create a category on UIImageView:
#interface UIImageView (Utils)
- (void)setImageRenderingMode:(UIImageRenderingMode)renderMode;
#end
#implementation UIImageView (Utils)
- (void)setImageRenderingMode:(UIImageRenderingMode)renderMode
{
NSAssert(self.image, #"Image must be set before setting rendering mode");
self.image = [self.image imageWithRenderingMode:renderMode];
}
#end
(Swift 4) Create an extension for UIImageView:
extension UIImageView {
func setImageRenderingMode(_ renderMode: UIImage.RenderingMode) {
assert(image != nil, "Image must be set before setting rendering mode")
// AlwaysOriginal as an example
image = image?.withRenderingMode(.alwaysOriginal)
}
}
Then in the Identity Inspector in the xib file, add a runtime attribute:

Using the template rendering mode with a UIImageView in a storyboard or xib is very buggy, both on iOS 7 and iOS 8.
On iOS 7
The UIImage is not properly decoded from the storyboard/xib. If you inspect the imageView.image.renderingMode property in the viewDidLoad method, you will notice that it is always UIImageRenderingModeAutomatic, even if you set it to Render As Template Image in your xcassets file.
To workaround, you have to manually set the rendering mode:
self.imageView.image = [self.imageView.image imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate];
On iOS 8
The UIImage is properly decoded and its renderingMode property reflects what was chosen in the xcassets file but the image is not tinted.
To workaround, you have two options:
Set the tintColor property in the User Defined Runtime Attributes instead of the Attributes inspector pane.
or
Manually reset the tintColor:
UIColor *tintColor = self.imageView.tintColor;
self.imageView.tintColor = nil;
self.imageView.tintColor = tintColor;
You can pick your preferred option, both properly tint the image.
(If you are compiling with Xcode 6.2, just doing self.imageView.tintColor = self.imageView.tintColor; is enough but this doesn’t work anymore if you are compiling with Xcode 6.3)
Conclusion
If you need to support both iOS 7 and iOS 8, you’ll need both workarounds. If you only have to support iOS 8, only one workaround is needed.

Setting imageView RenderingMode to use the tint color in the storyboard can be reduced to a one-liner:
[self.imageView setImage:[self.imageView.image imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate]];
Then the image and tint color can all be set in the Storyboard.

You may fix .xib issues with an extension:
import UIKit
// fixing Bug in XCode
// http://openradar.appspot.com/18448072
extension UIImageView {
override open func awakeFromNib() {
super.awakeFromNib()
self.tintColorDidChange()
}
}
Source: https://gist.github.com/buechner/3b97000a6570a2bfbc99c005cb010bac
Amazing, this bug has been around for like 4-5 years now.

You cann't set renderingMode either from storyboard or xib. It could access by programmatically.
ex:
UIImage *unSeletedImage = [UIImage imageNamed:#"UnSelected.png"];
selectedImage = [selectedImage imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];

Set tintColor & Class in Storyboard.
//
// TintColoredImageView.swift
// TintColoredImageView
//
// Created by Dmitry Utmanov on 14/07/16.
// Copyright © 2016 Dmitry Utmanov. All rights reserved.
//
import UIKit
#IBDesignable class TintColoredImageView: UIImageView {
override var image: UIImage? {
didSet {
let _tintColor = self.tintColor
self.tintColor = nil
self.tintColor = _tintColor
}
}
override init(frame: CGRect) {
super.init(frame: frame)
initialize()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
initialize()
}
override init(image: UIImage?) {
super.init(image: image)
initialize()
}
override init(image: UIImage?, highlightedImage: UIImage?) {
super.init(image: image, highlightedImage: highlightedImage)
initialize()
}
func initialize() {
let _tintColor = self.tintColor
self.tintColor = nil
self.tintColor = _tintColor
}
}

It's very easy to fix
Just create class UIImageViewPDF and use it in your storyboard
IB_DESIGNABLE
#interface UIImageViewPDF : UIImageView
#end
#implementation UIImageViewPDF
- (void) didMoveToSuperview
{
[super didMoveToSuperview];
self.image = [self.image imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate];
id color = self.tintColor;
self.tintColor = color;
}
#end

Another solution is to create a UIImageView subclass:
final class TemplateImageView: UIImageView {
override func awakeFromNib() {
super.awakeFromNib()
guard let oldImage = image else { return }
image = nil
image = oldImage.withRenderingMode(.alwaysTemplate)
}
}
Then just set the class in the Interface Builder to TemplateImageView.

Simple way to be set from Storyboard:
#IBDesignable
public class CustomImageView: UIImageView {
#IBInspectable var alwaysTemplate: Bool = false {
didSet {
if alwaysTemplate {
self.image = self.image?.withRenderingMode(.alwaysTemplate)
} else {
self.image = self.image?.withRenderingMode(.alwaysOriginal)
}
}
}
}
Works fine on iOS 10 and Swift 3

I got fixed this issue by adding runtime attribute tintColor in interface builder.
NOTE : You will still need to set your image to be rendered as a template image in your Images.xcassets file.

In iOS 9 setting the tintColor property in Interface Builder is still buggy.
Note that a working solution besides writing lines directly modifying ImageView properties is to set Render As: Template Image in the asset catalog, and call e.g.:
[[UIImageView appearanceWhenContainedInInstancesOfClasses:#[[MyView class]]] setTintColor:[UIColor whiteColor]];

If you create an IBOutlet you can change it in your awakeFromNib method like so...
self.myImageView.image = [self.myImageView.image imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate];
While #Moby's answer is more correct - this might be more succinct.

Crazy this bug is still in iOS 12.1! For storyboards/xibs: Adding a tag to the UIImageView can be a quick fix.
Swift 4.2
view.viewWithTag(1)?.tintColorDidChange()

extension UIImageView {
#IBInspectable var renderModeTemplate : Bool {
get{
return image?.renderingMode == .alwaysTemplate
}
set{
image = image?.withRenderingMode(newValue ? .alwaysTemplate:.alwaysOriginal)
}
}
}
In storyboard select UIImageView and select inspector, set property renderModeTemplate = On
In Storyboard

As Rudolf also mentioned above, I would define a simple class, like this:
import UIKit
#IBDesignable class TintImage: UIImageView{
override func layoutSubviews() {
super.layoutSubviews()
image = image?.withRenderingMode(.alwaysTemplate)
}
}
After this definition, just add an Image View to storyboard and select its custom class as TintImage. This will activate the "Tint" selection in the storyboard.

Related

clipsToBounds causes UIImage to not display in iOS10 & XCode 8

I switched my project over to new beta versions of iOS 10 and XCode 8. In all three areas of my app where I use:
imageView.layer.cornerRadius = imageView.frame.size.width/2
imageView.clipsToBounds = true
The associated images are not displaying at all. I have attempted cleaning the project as well as the build folder, restarting the device, trying on various simulators, re-adding the imageView, programmatically setting the associated UIImage instead of choosing one from the assets.
Removing the clipsToBounds line shows the rectangular image regardless of whether masksToBounds is true or false. How can I make a circular image in XCode8 / iOS10 ?
Edit: The project is Swift 2.x and not yet updated to Swift 3.0 syntax.
I had the same problem and calling layoutIfNeeded before all the rounded corner / clipsToBounds stuff fixed the issue. iOS 10 GM with xcode 8 GM causes views to disappear due to roundedCorners & clipsToBounds
This problem also happened to me.
I moved these code imageView.layer.cornerRadius = imageView.frame.size.width/2 from - (void)awakeFromNib to - (void)drawRect:(CGRect)rect and this problem went away.
My imageView is sized by autolayout. I think that height and width are not decided when awaking from nib on iOS 10.
This sounds like it could be due to a new bug since iOS 10 and Xcode 8 where views are initialised at size 1000x1000 and when trying to set corner radius to half your frame, it is setting it to 500 instead. This is documented further in this question here: Since Xcode 8 and iOS10, views are not sized properly on viewDidLayoutSubviews. My reason for thinking this is the fix to the 1000x1000 issue it to call layout subviews before doing anything that requires sizes for something that has been constructed on the interface builder.
I had the same problem. Not showing on the phone, but perfect on Storyboard and UI debugger. It was also working when I was putting the project "Opens with Xcode 7" instead of 8 but wasn't a satisfying solution. So I digged and found out the problem. The trouble was with a class looking like this :
#IBDesignable public class MyButton: UIButton {
#IBInspectable var styleName: String = "" {
didSet {
switch styleName {
case "RoundedLight":
tintColor = UIColor.lightPinkColor()
layer.borderColor = UIColor.whiteColor().CGColor
layer.borderWidth = 1
layer.masksToBounds = true
default:
break
}
}
}
override public func layoutSubviews() {
super.layoutSubviews()
switch styleName {
case "RoundedLight":
layer.cornerRadius = frame.height / 2
default:
break
}
}
}
I changed it to this and it works now :
#IBDesignable public class MyButton: UIButton {
#IBInspectable var styleName: String = "" {
didSet {
layoutIfNeeded()
}
}
override public func layoutSubviews() {
super.layoutSubviews()
switch styleName {
case "RoundedLight":
tintColor = UIColor.lightPinkColor()
layer.borderColor = UIColor.whiteColor().CGColor
layer.borderWidth = 1
layer.cornerRadius = frame.height / 2
layer.masksToBounds = true
default:
break
}
}
}
Note that none of the above worked for me, and I mean :
Calling layoutIfNeeded in the layoutSubviews()
Calling layoutIfNeeded in the awakeFromNib of my button (or my cell containing the button)
Calling layoutIfNeeded in the layoutSubview of my cell
Calling contentView.layoutIfNeeded() in the awakeFromNib of my cell
Calling view.layoutIfNeeded() in my view controller
I had ImageView that is fully circular in shape. Below is code :
//MARK:- Misc functions
func setProfileImage() {
imgProfile.layer.masksToBounds = false
imgProfile.layer.cornerRadius = imgProfile.frame.size.height/2
imgProfile.clipsToBounds = true
imgProfile.contentMode = UIViewContentMode.ScaleToFill
}
This works fine in iOS 9. However, in iOS 10 Xcode 8 the ImageView disappears.
After debugging found that ClipsToBound is culprit.
So placed the code in viewDidLayoutSubviews() resolved the issue.
override func viewDidLayoutSubviews() {
setProfileImage()
}
You can also use self.view.layoutIfNeeded()
It might be a layout issue. Setting clipToBounds to false would show the image even if its size is zero. Can you print the frame of your images?
If you set the cornerRadius and clipToBounds properties in viewDidLoad, try doing it in viewDidLayoutSubviews().
You could also try to call self.view.layoutIfNeeded().
Using obj-c, moving the syntax from viewDidLoad to viewDidLayoutSubviews worked for me.
I just implemented corner rounding like this
#implementation RoundImageView
- (instancetype)initWithCoder:(NSCoder *)coder
{
self = [super initWithCoder:coder];
if (self) {
self.layer.masksToBounds = YES;
self.layer.cornerRadius = MIN(self.bounds.size.height, self.bounds.size.width)/2;
[self addObserver:self
forKeyPath:#"bounds"
options:NSKeyValueObservingOptionNew
context:(__bridge void * _Nullable)(self)];
}
return self;
}
-(void)dealloc
{
[self removeObserver:self
forKeyPath:#"bounds"
context:(__bridge void * _Nullable)(self)];
}
-(void)observeValueForKeyPath:(NSString *)keyPath
ofObject:(id)object
change:(NSDictionary<NSString *,id> *)change
context:(void *)context
{
if(context == (__bridge void * _Nullable)(self) && object == self && [keyPath isEqualToString:#"bounds"])
{
self.layer.cornerRadius = MIN(self.bounds.size.height, self.bounds.size.width)/2;
}
}
#end
so I always have properly rounded corners.
And I hadn't issues on upgrading to iOS10 and XCode8
I think the problem happens because we set the round corner and clip subviews as #Pranoy C said.
I solved the problems by using layoutIfNeeded for the my tableview cell showing a user's profile picture. I want to ensure the image is round corner
Code is as follow:
- (void)awakeFromNib {
[super awakeFromNib];
[self layoutIfNeeded];
[self.inputIndicator_imageView.image imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate];
self.profile_pic_edit_imageView.layer.cornerRadius = self.profile_pic_edit_imageView.frame.size.width/2;
self.profile_pic_edit_imageView.layer.borderWidth = 1.0;
self.profile_pic_edit_imageView.layer.borderColor = GRAY_COLOR_SUPER_LIGHT.CGColor;
self.profile_pic_edit_imageView.clipsToBounds = YES;}
You should call layoutSubviews() on the main view before call imageView.frame.size.width
[self.view layoutSubviews];
imageView.layer.cornerRadius = imageView.frame.size.width/2
imageView.clipsToBounds = true

UITextField set border color using storyboard

I'd like to set border color using storyboard if possible. I've seen answer here: UITextField border color
And I followed answer in storyboard:
All properties set, but TextField doesn't show border. Any suggestions?
Well as Bogdan pointed out, you could very well do that with simple subclassing and just a few bits of code. After that everything will be editable in Storyboards.
Subclass UITextField
Create two properties, one for border width and one for border color
Make those variables IBInspectable and entire class IBDesignable
You'll be able to change color and width of border and see the change in real time.
Code for illustration (Swift 3.1):
#IBDesignable
class FormTextField: UITextField {
#IBInspectable var borderColor: UIColor? {
didSet {
layer.borderColor = borderColor?.cgColor
}
}
#IBInspectable var borderWidth: CGFloat = 0 {
didSet {
layer.borderWidth = borderWidth
}
}
}
Edit: You'll see this in your Attributes Inspector
As Bogdan pointed out it's true that you can't find the layer.borderColor property in storyboard as it's a run time thing.
However still you can set the borderColor without using IB_DESIGNABLE, on any view(or UIView Subclass) with a little bit of coding.
Below are the steps how to achieve it,
Create a category on CALayer class. Declare a property of type UIColor with a suitable name, I'll name it as borderUIColor .
Write the setter and getter for this property.
In the 'Setter' method just set the "borderColor" property of layer to the new colors CGColor value.
In the 'Getter' method return UIColor with layer's borderColor.
P.S: Remember, Categories can't have stored properties. 'borderUIColor' is used as a calculated property, just as a reference to achieve what we're focusing on.
Please have a look at the below code sample;
Objective C:
Interface File:
#import <QuartzCore/QuartzCore.h>
#import <UIKit/UIKit.h>
#interface CALayer (BorderProperties)
// This assigns a CGColor to borderColor.
#property (nonatomic, assign) UIColor* borderUIColor;
#end
Implementation File:
#import "CALayer+BorderProperties.h"
#implementation CALayer (BorderProperties)
- (void)setBorderUIColor:(UIColor *)color {
self.borderColor = color.CGColor;
}
- (UIColor *)borderUIColor {
return [UIColor colorWithCGColor:self.borderColor];
}
#end
Swift 3.1:
extension CALayer {
var borderUIColor: UIColor {
set {
self.borderColor = newValue.cgColor
}
get {
return UIColor(cgColor: self.borderColor!)
}
}
}
And finally go to your storyboard/XIB, follow the remaining steps;
Click on the View object for which you want to set border Color.
Click on "Identity Inspector"(3rd from Left) in "Utility"(Right side of the screen) panel.
Under "User Defined Runtime Attributes", click on the "+" button to add a key path.
Set the type of the key path to "Color".
Enter the value for key path as "layer.borderUIColor". [Remember this should be the variable name you declared in category, not borderColor here it's borderUIColor].
Finally chose whatever color you want.
Edit: You've to set layer.borderWidth property value to at least 1 to see the border color.
Build and Run.
Happy Coding. :)
I'm not sure you can change the border colour of a UITextfield in storyboard. You can change it programmatically with something along the lines of;
UITextField *myTextField = (UITextField *)[self.view viewWithTag:1];
myTextField.borderStyle = UITextBorderStyleLine;
myTextField.layer.borderWidth = 2;
myTextField.layer.borderColor = [[UIColor redColor] CGColor];
Hope this helps.
Adition to markus, put the full code:
import UIKit //IMPORTANT
#IBDesignable
class BorderTextField: UITextField {
#IBInspectable var borderColor: UIColor? {
didSet {
layer.borderColor = borderColor?.cgColor
}
}
#IBInspectable var borderWidth: CGFloat = 0 {
didSet {
layer.borderWidth = borderWidth
}
}
}
This is a variant over #rameswar answer which I think it's correct. Since we're applying a UIColor, I think it's preferable to write an extension for the UITextField instead (UI things together):
extension UITextField {
var borderColor : UIColor? {
get {
if let cgcolor = layer.borderColor {
return UIColor(CGColor: cgcolor)
} else {
return nil
}
}
set {
layer.borderColor = newValue?.CGColor
// width must be at least 1.0
if layer.borderWidth < 1.0 {
layer.borderWidth = 1.0
}
}
}
}
The runtime property would be then borderColor (so you don't need to type layer. and I think it's a bit cleaner than borderUIColor).
The borderColor of CALayer is optional so it's this property. It gets black when set to nil
And finally, the layer.borderWidth it's set to a minimum 1.0 because the color it's not set otherwise.
It doesn't show any border because of the layer.borderColor property. It's of type CGColor and Runtime attributes doesn't yet support that by default so, setting just one attribute wrong, disables the other ones as well.
To do it from the storyboard but also involving some code and subclassing, you can use this method:
Subclass UITextField and make an IB_DESIGNABLE UIColor property, that you'll then transform into CGColor and apply it to self.layer.borderColor.

UIView Background Image not showing

I've defined a bg image in the Xcode Images.xcassets and want to use it as background for a view but the bg stays black. I'm using:
override func viewDidLoad()
{
super.viewDidLoad();
view.backgroundColor = UIColor(patternImage: UIImage(named: "background_ipad"));
}
this should work according to some other tickets on SO but for some reason the background stays black, not showing the image. Any ideas why this would happen?
Use this code:
SWIFT
view.layer.contents = UIImage(named:"Image_Name").CGImage
Objective-C
view.layer.contents = (__bridge id _Nullable)([UIImage imageNamed:#"Image_Name"].CGImage);
Click on the catalog image
and ensure target membership
For objective C
self.view.layer.contents = (__bridge id _Nullable)([UIImage imageNamed:#"Image_Name"].CGImage);
For Swift
self.view.layer.contents = UIImage(named:"Image_Name")!.CGImage

How to make iOS Button give visual feedback when pressed?

I am making an iOS 7 app, I know that Apple's new design guidelines call for a bunch of flat design minimalist stuff, but this app is not really targeted at the tech-savvy crowd, so apple's guidelines pose a problem. I have a regular button, with just text in it, and I would like to put an outline around it, and I would also like for the button to react to being pressed, so that people actually know it is a button, and so that they do not freak out when the button takes them to a different app? So how do I
Put an outline around a regular iOS button?
Make a regular iOS Button give some simple visual feedback to being pressed?
Simplest way: make the UIButton's type be "System", rather than "Custom". A system button's image and/or text will highlight when touched.
You should do this in Interface Builder, by changing button's "Type" to be "System"
However, if you need to do it programmatically, you can do:
UIButton *button = [UIButton buttonWithType:UIButtonTypeSystem];
As for the UIButton's border, you can do:
- (void)viewDidLoad {
[super viewDidLoad];
self.button.layer.cornerRadius = 5;
self.button.layer.borderColor = [UIColor blackColor];
self.button.layer.borderWidth = 1;
}
If you are using a storyboard (interface builder) for designing your app it's quite easy:
Create a subclass of UIButton. Let's call it XYBorderButton.
In XYBorderButton.m add the methods:
- (id)initWithCoder:(NSCoder *)aDecoder {
self = [super initWithCoder:aDecoder];
if (self) {
[self makeBorder];
}
return self;
}
- (void)makeBorder {
self.layer.cornerRadius = 10.0;
self.layer.borderColor = [UIColor blueColor];
self.layer.borderWidth = 1.0;
}
Then in interface builder select the button and change its class to XYBorderButton
You can give visual feedback for example by changing the button's background color and/or by changing its font color.
Setting these attributes is quite easy with Interface Builder:
Just select the button, then choose the state "Highlighted" in the state config dropdown menu and set the background color and font color as desired.
extension UIButton {
func provideVisualFeedback4press()
{
backgroundColor = cyan
alpha = 0
UIView .animate(withDuration: 0.1, animations: { [weak self] in
guard let s = self else {
return
}
s.alpha = 1
}, completion: { [weak self] completed in
if completed {
guard let s = self else {
return
}
s.backgroundColor = UIColor.white
}
})
}}
usage:
#objc func backAction(_ sender:UIButton!)
{
sender.provideVisualFeedback4press()
If you set the text or image properties of a UIButton, it'll automatically give feedback when pressed (the font color and image will go darker). However if you simply placed the button on top of some other controls, then you'll have to wire up to the Touch Down event and manually change the appearance to any control you want.

How can I change the image displayed in a UIImageView programmatically?

I have an IBOutlet to a UIImageView, but when I look at the UIImageView doc, I can't see any hints about programmatically changing it. Do I have to fetch an UIImage object from that UIImageView?
If you have an IBOutlet to a UIImageView already, then all you have to do is grab an image and call setImage on the receiver (UIImageView). Two examples of grabbing an image are below. One from the Web, and one you add to your Resources folder in Xcode.
UIImage *image = [[UIImage alloc] initWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:#"http://farm4.static.flickr.com/3092/2915896504_a88b69c9de.jpg"]]];
or
UIImage *image = [UIImage imageNamed: #"cell.png"];
Once you have an Image you can then set UIImageView:
[imageView setImage:image];
The line above assumes imageView is your IBOutlet.
That's it! If you want to get fancy you can add the image to an UIView and then add transitions.
P.S. Memory management not included.
Note that the NIB file doesn't wire up all the IBOutlets until the view has been added to the scene. If you're wiring things up manually (which you might be doing if things are in separate NIBs) this is important to keep in mind.
So if my test view controller has an "imageView" wired by a nib, this probably won't work:
testCardViewController.imageView.image = [UIImage imageNamed:#"EmptyCard.png"];
[self.view addSubview:testCardViewController.view];
But this will:
[self.view addSubview:testCardViewController.view];
testCardViewController.imageView.image = [UIImage imageNamed:#"EmptyCard.png"];
This worked for me
[ImageViewName setImage:[UIImage imageNamed: #"ImageName.png"]];
Make sure that the ImageView is declared properly in the .h file and is linked with the IB element.
imageView.image = [UIImage imageNamed:#"myImage.png"];
For the purpose of people who may be googling this to try to solve their problem, remember to properly declare the property in your header file and to synthesize the UIImageView in your implementation file... It'll be tough to set the image programmatically without getter and setter methods.
#import <UIKit/UIKit.h>
#interface YOURCONTROLLERNAME : UIViewController {
IBOutlet UIImageView *imageToDisplay;
}
#property (nonatomic, retain) IBOutlet UIImageView *imageToDisplay;
#end
and then in your .m :
#implementation YOURCONTROLLERNAME
#synthesize imageToDisplay;
//etc, rest of code goes here
From there you should be fine using something like the following to set your image.
[YOURCONTROLLER.imageToDisplay setImage:[UIImage imageNamed:value]];
Example in Swift:
import UIKit
class ViewController: UIViewController {
#IBOutlet var myUIImageView: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
}
#IBAction func myAction(sender: UIButton) {
let newImg: UIImage? = UIImage(named: "profile-picture-name")
self.myUIImageView.image = newImg
}
#IBAction func myAction2(sender: UIButton) {
self.myUIImageView.image = nil
self.myUIImageView.image = UIImage(data: NSData(contentsOfURL: NSURL(string: "http://url/image.png")!)!)
}
}
Following Jordan's advice (which should work actually), try to set the UIImageView to be visible:
[imageView setHidden: NO];
and also - don't forget to attach it to the main UIView:
[mainView addSubview: imageView];
and to bring to the front:
[mainView bringSubviewToFront: imageView];
Hope combining all these steps will help you solve the mystery.
My problem was that I tried to change the image in an other thread. I did like this:
- (void)changeImage {
backgroundImage.image = [UIImage imageNamed:#"img.png"];
}
Call with:
[self performSelectorOnMainThread : #selector(changeImage) withObject:nil waitUntilDone:NO];
Don't forget to call sizeToFit() after you change image if you then use size of UIImageView to set UIScrollView contentSize and/or compute zoom scale
let image = UIImage(named: "testImage")
imageView.image = image
imageView.sizeToFit()
scrollView.contentSize = imageView.bounds.size
If you want to set image to UIImageView programmatically then Dont Forget to add UIImageView as SubView to the main View.
And also dont forgot to set ImageView Frame.
here is the code
UIImageView *myImage = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 320, 460)];
myImage.image = [UIImage imageNamed:#"myImage.png"];
[self.view addSubview:myImage];
myUIImageview.image = UIImage (named:"myImage.png")
Working with Swift 5 (XCode 10.3) it's just
yourImageView.image = UIImage(named: "nameOfTheImage")
UIColor * background = [[UIColor alloc] initWithPatternImage:
[UIImage imageNamed:#"anImage.png"]];
self.view.backgroundColor = background;
[background release];
This question already had a lot of answers. Unfortunately none worked for me.
So for the sake of completenes I add what helped me:
I had multiple images with the same name - so I ordered them in sub folders. And I had the full path to the image file I wanted to show. With a full path imageNamed: (as used in all solutions above) did not work and was the wrong method.
Instead I now use imageWithContentsOfFile: like so:
self.myUIImage.image = [UIImage imageWithContentsOfFile:_currentWord.imageFileName];
Don't know, if anyone reads that far?
If so and this one helped you: please vote up.
;-)
To set image on your imageView use below line of code,
self.imgObj.image=[UIImage imageNamed:#"yourImage.png"];

Resources