Border around text UIButton - ios

I've a question about UIButton in iOS.
I use Apple UIButton from library and I need that it, when is pressed become "selected" and its background is blue.
I make anything and it 's working correctly, but around the "label" of title my color is more dark.
I try to set label background to clearColor but it isn't a color of label and I don't know which button subview is.
Any idea?
I use Objective-C, but if anyone has idea about Swift I understand too.
Thanks in advance

Write this code in
viewDidLoad()
self.btnDemo.layer.borderWidth = 1.0;
self.btnDemo.layer.borderColor = [UIColor grayColor].CGColor;
[self.btnDemo setTitle:#"ESTERNO" forState:UIControlStateNormal];
[self.btnDemo setTitle:#"ES" forState:UIControlStateHighlighted];
[self.btnDemo setBackgroundImage:[self imageWithColor:[UIColor clearColor]] forState:UIControlStateNormal];
[self.btnDemo setBackgroundImage:[self imageWithColor:[UIColor colorWithRed:0 green:0 blue:255 alpha:1.0]] forState:UIControlStateHighlighted];
[self.btnDemo setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
[self.btnDemo setTitleColor:[UIColor whiteColor] forState:UIControlStateHighlighted];
Here btnDemo is UiButton outlet
Below method for convert Color to image
- (UIImage *)imageWithColor:(UIColor *)color {
CGRect rect = CGRectMake(0.0f, 0.0f, 1.0f, 1.0f);
UIGraphicsBeginImageContext(rect.size);
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetFillColorWithColor(context, [color CGColor]);
CGContextFillRect(context, rect);
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return image;
}

Related

UIButton: set background of image view (without setting an image)

How can I change the background color of the image view on a UIButton but without setting an image? (so that I have for example a red square next to the button text).
When I simply set mybutton.imageView.backgroundColor = UIColor.red and set the constraints of the image view to 28x28px. I do not see the red square.
Thanks.
To clarify: I want to set the background color of only the image view on of the UIButton - I do not want to color the whole button!
You tagged your question as both Swift and Objective-C, so...
In Swift, you can use this extension to create a "blank" image with a specific color:
public extension UIImage {
public convenience init?(color: UIColor, size: CGSize = CGSize(width: 1, height: 1)) {
let rect = CGRect(origin: .zero, size: size)
UIGraphicsBeginImageContextWithOptions(rect.size, false, 0.0)
color.setFill()
UIRectFill(rect)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
guard let cgImage = image?.cgImage else { return nil }
self.init(cgImage: cgImage)
}
}
Then, to add a "red square next to the button text":
let btnImage = UIImage(color: .red, size: CGSize(width: 28, height: 28))
btn.setImage(btnImage, for: .normal)
If you need to do this in Obj-C, it's the same process:
- (UIImage *)imageWithColor:(UIColor *)color andSize:(CGSize)sz {
CGRect rect = CGRectMake(0.0f, 0.0f, sz.width, sz.height);
UIGraphicsBeginImageContext(rect.size);
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetFillColorWithColor(context, [color CGColor]);
CGContextFillRect(context, rect);
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return image;
}
and
UIImage *btnImage = [self imageWithColor:[UIColor redColor] andSize:CGSizeMake(28.0, 28.0)];
[_btn setImage:btnImage forState:UIControlStateNormal];
Note: make sure your UIButton type is set to Custom, or the image will be "tinted".
Use this code.
UIButton *button =[[UIButton alloc]initWithFrame:CGRectMake(85, 290,110,20)];
button.layer.cornerRadius = ROUND_BUTTON_WIDTH_HEIGHT/2.0f;
button.backgroundColor = [UIColor redColor];
button.titleLabel.textAlignment = NSTextAlignmentCenter;
button.titleLabel.font = [UIFont systemFontOfSize:11.0];
[button setTitle:#"Download" forState:UIControlStateNormal];
[button addTarget:self action:#selector(downloadBtnClicked:)forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:button];
You should make your own custom UIButton. Another solution would be to try tweaking the default one using the IB available options.
UIButton Image + Text IOS
UIButton *_button = [UIButton buttonWithType:UIButtonTypeCustom];
[_button setFrame:CGRectMake(0.f, 0.f, 128.f, 128.f)]; // SET the values for your wishes
[_button setCenter:CGPointMake(128.f, 128.f)]; // SET the values for your wishes
[_button setClipsToBounds:false];
[_button setBackgroundImage:[UIImage imageNamed:#"jquery-mobile-icon.png"] forState:UIControlStateNormal]; // SET the image name for your wishes
[_button setTitle:#"Button" forState:UIControlStateNormal];
[_button.titleLabel setFont:[UIFont systemFontOfSize:24.f]];
[_button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal]; // SET the colour for your wishes
[_button setTitleColor:[UIColor redColor] forState:UIControlStateHighlighted]; // SET the colour for your wishes
[_button setTitleEdgeInsets:UIEdgeInsetsMake(0.f, 0.f, -110.f, 0.f)]; // SET the values for your wishes
[_button addTarget:self action:#selector(buttonTouchedUpInside:) forControlEvents:UIControlEventTouchUpInside]; // you can ADD the action to the button as well like

How to hide 1px UINavigationBar hairline from the middle of the UINavigation Bar

I have added UINavigation bar with a background image.
But unfortunately an unwanted 1px hairline is displaying at the middle of the UINavigation Bar.
I want to hide that line, but it's not working. I have added following code.
self.navigationController.navigationBar.translucent = NO;
[self.navigationController.navigationBar setShadowImage:nil];
[self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:#"navBarImg.png"] forBarMetrics:UIBarMetricsDefault];
if you do not need to set the navigationbar become transparent, you can use the following code
[self.navigationController.navigationBar setBackgroundImage:[self imageFromColor:[UIColor colorWithRed:0 green:0 blue:0 alpha:1]] forBarPosition:UIBarPositionAny barMetrics:UIBarMetricsDefault];
and adding the following method to generate an uiimage.
- (UIImage *)imageFromColor:(UIColor *)color {
CGRect rect = CGRectMake(0, 0, 1, 1);
UIGraphicsBeginImageContext(rect.size);
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetFillColorWithColor(context, [color CGColor]);
CGContextFillRect(context, rect);
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return image;
}

Message sent to a deallocated instance when accessing a UIButton to disable it

This is my code for creating a UIButton,
- (void) setNavButton
{
self->_newbutton = [UIButton buttonWithType:UIButtonTypeCustom];
UIImage *myImage = [UIImage imageNamed:#"New#3x.png"];
UIImageView *imageView = [[[UIImageView alloc] initWithFrame:CGRectMake(0,0, 46,57)] autorelease];
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetAllowsAntialiasing(context, true);
CGContextSetShouldAntialias(context, true);
CGContextSetInterpolationQuality(context, kCGInterpolationHigh);
[imageView.layer setMinificationFilter:kCAFilterTrilinear];
[imageView.layer setAllowsEdgeAntialiasing:YES];
CGRect imageRect = CGRectMake(0,0, imageView.bounds.size.width+10, imageView.bounds.size.height);
UIGraphicsBeginImageContextWithOptions(imageRect.size, NO, [UIScreen mainScreen].scale);
[imageView.layer renderInContext:UIGraphicsGetCurrentContext()];
[myImage drawInRect:CGRectMake(0,12,myImage.size.width,myImage.size.height)];
myImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
[imageView setImage:myImage];
[self->_newbutton setImage:[imageView image] forState:UIControlStateNormal];
}
I have created property for this,and i accessing it in the same to disable it.But when is do so i get and error saying 'Message sent to a deallocated instance'. I am using the following code to disable it.
[self->_newbutton setEnabled:No];
Generate Button with _newbutton
_newbutton = [UIButton buttonWithType:UIButtonTypeCustom];
Also set image with _newbutton
[_newbutton setImage:[imageView image] forState:UIControlStateNormal];
Then set disable as
[self._newbutton setEnabled:No];

iOS UIButton with transparent title on white background

I have a custom UIButton with transparent background and white title.
I'm looking for a simple solution to invert it on highlight (white background and transparent title) as it is achieved on system UISegmentedControl.
Is there simpler solution than inverting alpha on snapshot used as a CALayer mask?
If not, could you tell how can I invert CALayer alpha?
You can draw the text on a CGContext using Destination Out as blend mode.
This code seems to work:
- (void)viewDidLoad
{
[super viewDidLoad];
self.view.backgroundColor = [UIColor greenColor];
UIFont* font = [UIFont fontWithName:#"Helvetica-Bold" size:18];
NSString* buttonText = #"BUTTON";
CGSize buttonSize = CGSizeMake(200, 50);
NSDictionary* textAttributes = #{NSFontAttributeName:font};
CGSize textSize = [buttonText sizeWithAttributes:textAttributes];
UIGraphicsBeginImageContextWithOptions(buttonSize, NO, [[UIScreen mainScreen] scale]);
CGContextRef ctx = UIGraphicsGetCurrentContext();
CGContextSetFillColorWithColor(ctx, [UIColor redColor].CGColor);
UIBezierPath *path = [UIBezierPath bezierPathWithRect:CGRectMake(0, 0, buttonSize.width, buttonSize.height)];
CGContextAddPath(ctx, path.CGPath);
CGContextFillPath(ctx);
CGContextSetBlendMode(ctx, kCGBlendModeDestinationOut);
CGPoint center = CGPointMake(buttonSize.width/2-textSize.width/2, buttonSize.height/2-textSize.height/2);
[#"BUTTON" drawAtPoint:center withAttributes:textAttributes];
UIImage* viewImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
UIImageView* imgView = [[UIImageView alloc] initWithImage:viewImage];
[self.view addSubview:imgView];
}
By the way, if you want to set the UIImage in a UIButton instead of just adding it to a view:
UIButton* boton = [[UIButton alloc] initWithFrame:CGRectMake(50, 50, viewImage.size.width, viewImage.size.height)];
[boton setBackgroundColor:[UIColor clearColor]];
[boton setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
boton.titleLabel.font = font;
[boton setTitle:buttonText forState:UIControlStateNormal];
[boton setImage:viewImage forState:UIControlStateHighlighted];
[self.view addSubview:boton];
You could set
-(void)viewDidload: {
[yourButton setTitleColor:(UIColor *)color
forState:UIControlStateHighlighted];
[yourButton addTarget:self
action:#selector(changeButtonBackGroundColor:)
forControlEvents:UIControlEventTouchDown];
}
-(void)changeButtonBackGroundColor:(UIButton *)button {
[button setBackgroundColor:[UIColor yourColor]];
}
remember to change it back with events: UIControlEventTouchUpInside and UIControlEventTouchOutSide :)

UIButton border that changes thickness when selected

I have a subclassed UIButton
- (void)configureButton
{
self.titleLabel.font = [UIFont systemFontOfSize:18.0f];
[self setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
CALayer *border = [CALayer layer];
border.backgroundColor = [UIColor whiteColor].CGColor;
border.frame = CGRectMake(0, self.frame.size.height, self.frame.size.width, 1.0);
[self.layer addSublayer:border];
}
- (void)setSelected:(BOOL)selected
{
[super setSelected:selected];
[self setTitleColor:[UIColor whiteColor] forState:UIControlStateSelected];
// remove all layers ?
if (selected) {
CALayer *border = [CALayer layer];
border.backgroundColor = [UIColor whiteColor].CGColor;
border.frame = CGRectMake(0, self.frame.size.height, self.frame.size.width,3.0);
[self.layer addSublayer:border];
self.titleLabel.font = [UIFont boldSystemFontOfSize:18.0f];
} else {
CALayer *border = [CALayer layer];
border.backgroundColor = [UIColor whiteColor].CGColor;
border.frame = CGRectMake(0, self.frame.size.height, self.frame.size.width,1.0);
[self.layer addSublayer:border];
self.titleLabel.font = [UIFont systemFontOfSize:18.0f];
}
}
The default state of the button has a 1.0 bottom border. When it is selected, the border should become 3.0. How can I clear the previously added layer and re add a 1.0 border when a user toggles a button?
I believe there is an easier way to do what you need. If you subclass the UIButton just because you just want to have different types button border, you can try a different way but a lot easier.
Use 2 different button background image, one with border 1 and another with border 3.
[self.button setBackgroundImage:[UIImage imageNamed:#"ImageWithBorder1"] forState:UIControlStateNormal];
[self.button setBackgroundImage:[UIImage imageNamed:#"ImageWithBorder3"] forState:UIControlStateHighlighted];
[self.button setBackgroundImage:[UIImage imageNamed:#"ImageWithBorder3"] forState:UIControlStateSelected];
With an additional button image, it might just take extra 10 kb on your project.

Resources