How to use template rendering mode in Xcode 6 Interface Builder? - ios

I'm trying to use images with template rendering mode enabled in Interface Builder but I can't get it working. With buttons everything works ok but with ImageViews the tintColor is not applying to the image.
I have enabled "Vectors type" (I'm using pdf) and "Render as Template Image" in the Image assets. What am I doing wrong?

I've hit the same problem. I think this is a bug.
You could dup this radar http://openradar.appspot.com/radar?id=5334033567318016, which refers to this minimal example app https://github.com/algal/TemplateImagesBrokenDemo.
I know of two workarounds for this problem
wrap in UIButton
Since tintColor works for UIButtons, one workaround is instead of UIImageView just to use a custom-type UIButton with userInteractionEnabled=false. If you disable the button's interactivity with UIView.userInteractionEnabled (as opposed to with UIControl.enabled), then you won't change the appearance of the image.
manually re-set the image in code
Another workaround is to re-set the .image property in code, after the UIImageView has been loaded from the nib. This works because setting an image in code seems to be what triggers the templating logic. For this to work, you need to re-set the image to its existing value in a way that won't be optimized away in the compiler. A snippet like this in awakeFromNib has worked for me:
override func awakeFromNib() {
super.awakeFromNib()
if shouldSetImagesManually {
// the following three-lines should in theory have no effect.
// but in fact, they ensure that the UIImageView
// correctly applies its tintColor to the vector template image
let image = self.templateImageView.image
self.templateImageView.image = nil
self.templateImageView.image = image
}

In my case the problem occures if the app is built with iOS8 SDK and is running on iOS 7.
My workaround is:
// this is the code that *should* work and does so on iOS 8
UIColor *tintColor = [UIColor colorWithWhite:1.0 alpha:0.3];
[self.iconImageView setTintColor:tintColor];
self.iconImageView.image = [self imageForIconImageView]; // image is loaded from a pdf-resource (asset catalog set as Template) with imageNamed:#"resourceName"
// this is the workaround to get tint on iOS 7
if (!IS_IOS8_OR_HIGHER) { // macros checking iOS version*
UIImage *templateImage = [self.iconImageView.image imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate];
self.iconImageView.image = templateImage;
}
// * - macros is defined like so:
// #define IS_IOS8_OR_HIGHER ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0)

Here's the simplest code-less solution I found:

Another workaround that seems to work for me is to set the controller.view's tintColor. To get the default system tint color working:
self.view.tintColor = self.view.tintColor;
Like #algal's solution, it shouldn't make a difference, but it does.

Related

(iOS) alpha not works when run app

I have hours trying to solve this and researching about this problem without results. This is my problem:
I'm using a ViewController in a existing project and over this I use an UIIMageView and a UIView at the same level. Then I set them alpha value in these two elements (alpha = 0.5) using Interface Builder. When I run the project on Simulator the alpha value not make effect and they looks like with their alpha value = 1. I made this same procedure in a new project and when I run the alpha effect is visible. I tried check/uncheck opaque option, set alpha value programatically as property or using method setAlpha, as well as set opaque value with code and it doesn't works. This problem happens with device too.
Anyone have a solution?
Check whether you import
#import <UIKit/UIKit.h>
UIIMageView.alpha = 0.4;
OR check with this
UIImage *wheelImage = [UIImage imageNamed:#"wheel#2x.png"];
UIImageView *imageView = [[UIImageView alloc]initWithImage:wheelImage];
imageView.frame = CGRectMake(50, 50, wheelImage.size.width, wheelImage.size.height);
imageView.alpha = 0.2;
[self.view addSubview:imageView];
Did you forget to connect your outlet in the storyboard and the property?

UIProgressView track and progress images not working in iOS7

I have a UIProgressView that has been customised with a progress and track image. I also customised the size of the progress view. This works fine in iOS 6. I am facing problems getting this to work in iOS7.
_progress.progressViewStyle = UIProgressViewStyleBar;
_progress.trackImage = [UIImage imageNamed:#"summary-progress-track.png"];
_progress.progressImage = [UIImage imageNamed:#"summary-progress.png"];
_progress.frame = CGRectMake(50, 50, 100, 10);
Not only is the height being ignored but the custom images do not get applied. I just get a blue tinted progress bar like this:
I think the default tint colour is somehow overriding the progress images. I have also tried setting this with UIAppearance but it did not work.
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
[[UIProgressView appearance] setProgressImage:[UIImage imageNamed:#"summary-progress.png"]];
[[UIProgressView appearance] setTrackImage:[UIImage imageNamed:#"summary-progress-track.png"]];
return YES;
}
Personally I use the MPProgressHUD for all progress tracking on a view. Here's the link to the download
https://github.com/jdg/MBProgressHUD
The usage is as simple as it get. Here's a tutorial you might like to check out.
http://code.tutsplus.com/tutorials/ios-sdk-uiactivityindicatorview-and-mbprogresshud--mobile-10530
The MPProgressHUD has a specific method to show custom images.
This should be helpful if you have not already seen this.
https://developer.apple.com/library/ios/documentation/UserExperience/Conceptual/UIKitUICatalog/UIProgressView.html#//apple_ref/doc/uid/TP40012857-UIProgressView-SW1
the blue color is the default tint color for the control in iOS7 that gets applied.
Found a solution. If anyone else is stuck on this check out this answer and suggested code to workaround the issue: UIProgressView custom track and progress images in iOS 7.1
I print the progress's subviews and find that one of them's frame width is 0,
so after
[_videoProgressView setProgress:progress animated:NO];
reset the track and progress images
UIImageView *trackImageView = _videoProgressView.subviews.firstObject;
UIImageView *progressImageView = _videoProgressView.subviews.lastObject;
CGRect trackProgressFrame = trackImageView.frame;
trackProgressFrame.size.height = _videoProgressView.frame.size.height;
trackImageView.frame = trackProgressFrame;
progressImageView.frame = trackProgressFrame;
progressImageView.image = progressImage;
trackImageView.image = trackImage;

Flip UIImageViews for Right to Left Languages

iOS automatically flips the entire ViewController when using a RTL language like Arabic and does a great job with most of the layout, especially text. The default behavior is to flip the layout but leave UIImageViews the same orientation (since you generally don't want to reverse images).
Is there a way to specify that some images should be flipped (such as arrows) when the phone is set to a RTL language?
iOS 9 includes the imageFlippedForRightToLeftLayoutDirection method that you can use, that automatically flips the image in a UIImageView when in an RTL localization.
The best solution I found to date is marking the image in the assets file as mirror.
We can use imageFlippedForRightToLeftLayoutDirection which returns flipped image if current language is RTL(right to left). i.e
Objective-c
UIImage * flippedImage = [[UIImage imageNamed:#"imageName"] imageFlippedForRightToLeftLayoutDirection];
Swift 3
let flippedImage = UIImage(named: "imageName")?.imageFlippedForRightToLeftLayoutDirection()
Source: Apple Docs
You have to manually flip the UIImages in the UIImageViews you want when the phone is set to a RTL language. This can be easily achieved with this code:
UIImage* defaultImage = [UIImage imageNamed:#"default.png"];
UIImage* flipImage = [UIImage imageWithCGImage:sourceImage.CGImage scale:1.0 orientation: UIImageOrientationUpMirrored];
myImageview.image = flipImage;
I ended up using localized images for the forward and back arrows. This had the advantage of not having to add code each place the image was used and gives the opportunity to clean up the arrows if there are gradients that don't work well flipped.
While we wait for iOS 9 improved right to left support you could create a UIImageView subclass and override setImage to mirror inside the images as #nikos-m suggests and calling super.image = flipImage.
That way you can easily set all the images views you want to flip using custom classes in Interface Builder instead of having to add IBOutlets.
Swift 5
If you want to individualize the image flip, you can register each image with the direction you want since the layout direction is a trait:
let leftToRight = UITraitCollection(layoutDirection: .leftToRight)
let rightToLeft = UITraitCollection(layoutDirection: .rightToLeft)
let imageAsset = UIImageAsset()
let leftToRightImage = UIImage(named: "leftToRightImage")!
let rightToLeftImage = UIImage(named: "rightToLeftImage")!
imageAsset.register(leftToRightImage, with: leftToRight)
imageAsset.register(rightToLeftImage, with: rightToLeft)
This is the same as configuring it in the asset catalogue as #SergioM answered.

Animated Resize of UIToolbar Causes Background to be Clipped on iOS <5.1

I have implemented a custom split view controller which — in principle — works quite well.
There is, however one aspect that does not work was expected and that is the resize-animation of the toolbar on iOS prior to version 5.1 — if present:
After subclassing UIToolbar to override its layoutSubviews method, animating changes to the width of my main-content area causes the toolbar-items to move as expected. The background of the toolbar — however — does not animate as expected.
Instead, its width changes to the new value immediately, causing the background to be shown while increasing the width.
Here are what I deem the relevant parts of the code I use — all pretty standard stuff, as little magic/hackery as possible:
// From the implementation of my Split Layout View Class:
- (void)setAuxiliaryViewHidden:(BOOL)hide animated:(BOOL)animated completion:(void (^)(BOOL isFinished))completion
{
auxiliaryViewHidden_ = hide;
if (!animated)
{
[self layoutSubviews];
if (completion)
completion(YES);
return;
}
// I've tried it with and without UIViewAnimationOptionsLayoutSubviews -- didn't change anything...
UIViewAnimationOptions easedRelayoutStartingFromCurrentState = UIViewAnimationOptionCurveEaseOut | UIViewAnimationOptionBeginFromCurrentState;
[UIView animateWithDuration:M_1_PI delay:0.0 options:easedRelayoutStartingFromCurrentState animations:^{
[self layoutSubviews];
} completion:completion];
}
- (void)layoutSubviews
{
[super layoutSubviews];
// tedious layout work to calculate the frames for the main- and auxiliary-content views
self.mainContentView.frame = mainContentFrame; // <= This currently has the toolbar, but...
self.auxiliaryContentView.frame = auxiliaryContentFrame; // ...this one could contain one, as well.
}
// The complete implementation of my UIToolbar class:
#implementation AnimatableToolbar
static CGFloat sThresholdSelectorMargin = 30.;
- (void)layoutSubviews
{
[super layoutSubviews];
// walk the subviews looking for the views that represent toolbar items
for (UIView *subview in self.subviews)
{
NSString *className = NSStringFromClass([subview class]);
if (![className hasPrefix:#"UIToolbar"]) // not a toolbar item view
continue;
if (![subview isKindOfClass:[UIControl class]]) // some other private class we don't want to f**k around with…
continue;
CGRect frame = [subview frame];
BOOL isLeftmostItem = frame.origin.x <= sThresholdSelectorMargin;
if (isLeftmostItem)
{
subview.autoresizingMask = UIViewAutoresizingFlexibleRightMargin;
continue;
}
BOOL isRightmostItem = (CGRectGetMaxX(self.bounds) - CGRectGetMaxX(frame)) <= sThresholdSelectorMargin;
if (!isRightmostItem)
{
subview.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin;
continue;
}
subview.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin;
}
}
#end
I’ve set the class of the toolbar in InterfaceBuilder and I know for a fact, that this code gets called and, like I said, on iOS 5.1 everything works just fine.
I have to support iOS starting version 4.2, though…
Any help/hints as to what I’m missing are greatly appreciated.
As far as I can see, your approach can only work on iOS SDK > 5. Indeed, iOS SDK 5 introduced the possibility of manipulating the UIToolbar background in an explicit way (see setBackgroundImage:forToolbarPosition:barMetrics and relative getter method).
In iOS SDK 4, an UIToolbar object has no _UIToolbarBackground subview, so you cannot move it around in your layoutSubviews implementation. To verify this, add a trace like this:
for (UIView *subview in self.subviews)
{
NSLog(#"FOUND SUBVIEW: %#", [subview description]);
run the code on both iOS 4 and 5 and you will see what I mean.
All in all, the solution to your problem lays in handling the background in two different ways under iOS 4 and iOS 5. Specifically, on iOS 4 you might give the following approach a try:
add a subview to your custom UIToolbar that acts as a background view:
[toolbar insertSubview:backgroundView atIndex:0];
set:
toolbar.backgroundColor = [UIColor clearColor];
so that the UIToolbar background color does not interfere;
in your layoutSubviews method animate around this background subview together with the others, like you are doing;
Of course, nothing prevents you from using this same background subview also for iOS 5, only thing you should beware is that at step 1, the subview should be inserted at index 1 (i.e, on top of the existing background).
Hope that this helps.
Since I think this is going to be useful for someone else, I’ll just drop my solution here for reference:
Per sergio’s suggestion, I inserted an additional UIImageView into the view hierarchy. But since I wanted this to work with the default toolbar styling, I needed to jump trough a few hoops:
The image needed to be dynamically generated whenever the tintColor changed.
On iOS 5.0.x the toolbar background is an additional view.
To resolve this I ended up…
Implementing +load to set a static BOOL on whether I need to do anything. (Parses -[UIDevice systemVersion] for version prior to 5.1).
Adding a (lazily loaded) property for the image view stretchableBackground. The view will be nilif my static flag is NO. Otherwise the view will be created having twice the width of [UIScreen mainScreen], offset to the left by half that width and resizable in height and right margin and inserted into the toolbar at index 0.
Overriding setTintColor:. Whenever this happens, I call through to super and __updateBackground.
Implemented a method __updateBackground that:
When the toolbar responds to backgroundImageForToolbarPosition:barMetrics: get the first subview that is not our stretchableBackground. Use the contents property of that view’s layer to populate the stretchableBackground’s image property and return.
If the toolbar doesn’t respond to that selector,
use CGBitmapContextCreate() to obtain a 32bit RGBA CGContextRef that is one pixel wide and as high as the toolbar multiplied by the screen’s scale. (Use kCGImageAlphaPremultipliedLast to work with the device RGB color space…)
Translate the CTM by that height and scale it by scale/-scale to transition from UIKit to CG-Coordinates and draw the view’s layer into that context. (If you fail to do this, your image will always be transparent blank…)
Create a UIImage from that context and set it as the stretchableBackground’s image.
Notice that this fix for iOS 5.0.x will not work as expected when using different background images for portrait and landscape or images that do not scale — although that can be tweaked by configuring the image view differently…

How do I create a textured background (image palette) color like grouped tableview background color?

I was wondering if anyone knows how to setup a new textured color in the palette. See the image below.
I tried to click on Other.... and then put a image palette on. like so:
So now I can select only one pixel out of it. I wish I could select more. It would make the work a lot easier instead of setting the background programatically every time.
If you have any suggestions of things I can try such as files to override or anything please help...
Thanks.
Programatically is kinda easy. But I'm making a universal app (iphone and Ipad) and... well there must be a way around it.
Here's how I do it programatically:
UIImage *wood = [UIImage imageNamed:#"woodenBack.png"];
self.tableView.backgroundColor = [UIColor colorWithPatternImage:wood];
Can use something like this,
BOOL large = ([UIDevice currentDevice].userInterfaceIdiom == UIUserInterfaceIdiomPad); // Page thumb size
if(large){
UIImage *wood = [UIImage imageNamed:#"woodenBack.png"];
self.tableView.backgroundColor = [UIColor colorWithPatternImage:wood];
}else{
UIImage *brick = [UIImage imageNamed:#"brick.png"];
self.tableView.backgroundColor = [UIColor colorWithPatternImage:brick];
}
if the background persists across all views then you can possibly apply the background to the UIWindow in your appdelegate and set background color clear color in the rest of the views.
Another approach is to loop and browse through the subviews and find tableview and apply background to the tableview, but I guess this is a CPU intensive task and it is better to have image loaded using code.

Resources