I want to set a Dotted / Dashed border for my UITextField and UITextView.
How can I do that? I know that, I can set border with this line of code:
[self.textFieldCardTitle.layer setBorderWidth:1.0];
[self.textFieldCardTitle.layer setBorderColor:[[UIColor whiteColor] CGColor]];
Notice: I already have the idea to add a UIImageView behind the UITextView and set there an image with dashed border. But I don't want to solve it that way.
You could try, for example, next approach:
1) Create image that will represent your border (for example: one dot and space)
2) Add image to project.
3) Set border (as in code in your question) and set color with pattern:
[self.textFieldCardTitle.layer setBorderWidth:6.0];
[self.textFieldCardTitle.layer setBorderColor:[[UIColor colorWithPatternImage:[UIImage imageNamed:#"dashed_white.png"]] CGColor]];
As border is drawn along 4 sides (left, right, bottom, top) you should use square image: for example, pixel in middle is black and pixels around it are transparent. So copies of that image will be placed around the view.
Just use following code for Dotted / Dashed Border around UIView or UITextField or any other view:-
CAShapeLayer * _border = [CAShapeLayer layer];
_border.strokeColor = [UIColor redColor].CGColor;
_border.fillColor = nil;
_border.lineDashPattern = #[#4, #2];
[YOURVIEW.layer addSublayer:_border];
//for a square effect
_border.path = [UIBezierPath bezierPathWithRect:YOURVIEW.bounds].CGPath;
//for a rounded effect
//_border.path = [UIBezierPath bezierPathWithRoundedRect:YOURVIEW.bounds cornerRadius:txtUserName.frame.size.height / 2].CGPath;
_border.frame = YOURVIEW.bounds;
For more details, Refer this Answer.
Hope, this is what you're looking for. Any concern get back to me. :)
Here's what I did with Swift:
self.textFieldCardTitle.layer.borderWidth = 3
self.textFieldCardTitle.layer.borderColor = (UIColor(patternImage: UIImage(named: "dot")!)).CGColor
Free bonus, I attached the pics below. Unless StackOverflow changes its background, you probably won't see them as they are white squares on a white background, so you'll find the urls below as well.
http://i.stack.imgur.com/X7PfM.png -> rename it to dot.png
http://i.stack.imgur.com/IemhF.png -> rename it to dot#2x.png
http://i.stack.imgur.com/CSjZT.png -> rename it to dot#3x.png
Swift 5, for #Meet Doshi's answer
class CustomTextField: UITextField{
let dashBorder = CAShapeLayer()
override init(frame: CGRect) {
super.init(frame: .zero)
dashBorder.strokeColor = UIColor.lightGray.cgColor
dashBorder.fillColor = nil
dashBorder.lineDashPattern = [4, 2]
layer.addSublayer(dashBorder)
}
override func layoutSubviews() {
super.layoutSubviews()
dashBorder.path = UIBezierPath(roundedRect: bounds, cornerRadius: 5).cgPath
dashBorder.frame = bounds
}
}
Related
I have SVG file and i was able to access SVG's shapes using SVGKit.
Now, I have CAShapeLayer which may contain circle, square or any closed shape.
I want to add CATextLayer on CAShapeLayer in such way that text should not cross the defined shape.
Here is the example of crossing CATextLayer on CAShapeLayer :
It's crossing just because, CATextLayer is starting from 0 position of CAShapeLayer which contains circle in particular this case.
In my case, CAShapeLayer can contain any closed shape. It can be oval also.
How can I identify shape inside CAShapeLayer? or How can I apply path to CATextLayer? which will makes sure text will be drawn inside shape?
Here is code to add CATextLayer On CAShapeLayer:
-(CATextLayer *)addTrackerNumberToLayer:(NSString *)numbers{
self.numbersTextLayer = [CATextLayer new];
self.numbersTextLayer.foregroundColor = [UIColor blackColor].CGColor;
self.numbersTextLayer.font = (__bridge CFTypeRef _Nullable)([UIFont boldSystemFontOfSize:15]);
self.numbersTextLayer.fontSize=25;
self.numbersTextLayer.anchorPoint = CGPointZero;
self.numbersTextLayer.frame = CGRectMake(self.parentShapeLayer.bounds.size.width*0.05, self.parentShapeLayer.bounds.size.height*0.05, self.parentShapeLayer.bounds.size.width*0.90, self.parentShapeLayer.bounds.size.height*0.30);
self.numbersTextLayer.position = CGPointMake(self.parentShapeLayer.bounds.size.width*0.05,self.parentShapeLayer.bounds.size.height*0.05);
self.numbersTextLayer.alignmentMode = kCAAlignmentCenter;
[self.parentShapeLayer addSublayer:self.numbersTextLayer];
}
Use isWrapped property of CATextLayer this determines whether the text is wrapped to fit within the receiver’s bounds.
-(CATextLayer *)addTrackerNumberToLayer:(NSString *)numbers{
self.numbersTextLayer = [CATextLayer new];
self.numbersTextLayer.foregroundColor = [UIColor blackColor].CGColor;
self.numbersTextLayer.font = (__bridge CFTypeRef _Nullable)([UIFont boldSystemFontOfSize:15]);
self.numbersTextLayer.fontSize=25;
self.numbersTextLayer.anchorPoint = CGPointZero;
self.numbersTextLayer.frame = CGRectMake(self.parentShapeLayer.bounds.size.width*0.05, self.parentShapeLayer.bounds.size.height*0.05, self.parentShapeLayer.bounds.size.width*0.90, self.parentShapeLayer.bounds.size.height*0.30);
self.numbersTextLayer.position = CGPointMake(self.parentShapeLayer.bounds.size.width*0.05,self.parentShapeLayer.bounds.size.height*0.05);
self.numbersTextLayer.alignmentMode = kCAAlignmentCenter;
[self.numbersTextLayer setWrapped:YES];//User Wrapped to YES to imbound the text to fit in the region.
[self.parentShapeLayer setMasksToBounds:YES];
[self.parentShapeLayer addSublayer:self.numbersTextLayer];
return self.numbersTextLayer;
}
I must add a UIImageView as subview of MapView. To do this I created a layer above the MapView. In this layer I want to put my image, but I get a white rectangle and nothing else. My image is not visible.
This is the code:
- (void)viewDidLoad
{
//......
CALayer *layer = [CALayer layer];
layer.backgroundColor = [[UIColor whiteColor] CGColor];
if(UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone)
{
layer.bounds = CGRectMake(self.mapView.bounds.origin.x,
self.mapView.bounds.origin.y, 80, 300);
}
else
{
layer.bounds = CGRectMake(self.mapView.frame.origin.x,
self.mapView.frame.origin.y, 150, 700);
}
layer.contents = (id)[UIImage imageNamed:#"myImage.png"];
//the name is correct but in the output the image is not visible
[[self.mapView layer] addSublayer:layer];
[layer setNeedsDisplay];
}
This is a general answer for the sake of future viewers. It is based on the question title rather than the details of the original question.
How to add a UIImage to a CALayer
You can add an image to a view's layer simply by using its contents property:
myView.layer.contents = UIImage(named: "star")?.cgImage
Note that the UIImage needs to be converted to a CGImage.
If you wish to add the image in its own layer, you can do it like this:
let myLayer = CALayer()
let myImage = UIImage(named: "star")?.cgImage
myLayer.frame = myView.bounds
myLayer.contents = myImage
myView.layer.addSublayer(myLayer)
Modifying the appearance
The above code produces a view like this. The light blue is the UIView and the dark blue star is the UIImage.
As you can see, though, it looks pixelated. This is because the UIImage is smaller than the UIView so it is being scaled to fill the view, which is the default it you don't specify anything else.
The examples below show variations on the layer's contentsGravity property. The code looks like this:
myView.layer.contents = UIImage(named: "star")?.cgImage
myView.layer.contentsGravity = kCAGravityTop
myView.layer.isGeometryFlipped = true
In iOS, you may want to set the isGeometryFlipped property to true if you are doing anything with top or bottom gravity, otherwise it will be the opposite of what you expect. (Only the gravity is flipped vertically, not the content rendering. If you are having trouble with the content being flipped, see this answer.)
There are two UIView examples below for every contentsGravity setting, one view is larger than the UIImage and the other is smaller. This way you can see the effects of the scaling and gravity.
kCAGravityResize
This is the default.
kCAGravityResizeAspect
kCAGravityResizeAspectFill
kCAGravityCenter
kCAGravityTop
kCAGravityBottom
kCAGravityLeft
kCAGravityRight
kCAGravityTopLeft
kCAGravityTopRight
kCAGravityBottomLeft
kCAGravityBottomRight
Related
Content mode property of a view
Drawing a UIImage in drawRect with CGContextDrawImage
CALayer Tutorial: Getting Started
it has to be
layer.contents = (id)[UIImage imageNamed:#"myImage.png"].CGImage;
You can only put a CGImage into a layer, not an UIImage directly.
I removed
[layer setNeedsDisplay];
I do not know why, but it works!
You need to set the frame of the CALayer properly, because the default is CGRectZero.
2020, full simple examples
In this example, the image is simply the size of the overall view:
class ImageyView: UIView {
private lazy var im: CALayer = {
let l = CALayer()
l.contents = UIImage(named: "some_background")?.cgImage
l.contentsGravity = .resizeAspect
layer.addSublayer(l)
return l
}()
override func layoutSubviews() {
super.layoutSubviews()
im.frame = bounds
}
}
In this example it's a Button, with small icon you're adding at the top left:
class BroadcastButton: UIButton {
private lazy var im: CALayer = {
let l = CALayer()
l.contents = UIImage(named: "your_icon")?.cgImage
l.contentsGravity = .resizeAspect
layer.addSublayer(l)
return l
}()
override func layoutSubviews() {
super.layoutSubviews()
im.frame = CGRect(origin: CGPoint(x: 2, y: 2),
size: CGSize(width: 14, height: 14))
}
}
myView.layer.contents = UIImage(named: "star")?.cgImage
This should be a comment, but I lost few hours, so I'm making it a stand alone answer.
I was doing:
myView.layer.contents = UIImage(named: "star")
can you find what the problem is? Because contents is of type Any then this just compiles fine. But the correct code is:
myView.layer.contents = UIImage(named: "star").cgImage
I wonder if anybody have an example for Glow effect for font? I tried to look in NSAttributedString but I don't find in attribute for glowing text.
Try this:
#include <Quartzcore/Quartzcore.h>
.......
yourLabel.layer.shadowColor = [[UIColor glowColor] CGColor]; //Replace glowColor with the desired color (redColor, greenColor, etc.)
yourLabel.layer.shadowOffset = CGSizeMake(0.0, 0.0); //The glow starts from the center
yourLabel.layer.shadowRadius = 20.0; //You can change this to the desired amount
yourLabel.layer.shadowOpacity = 0.5; //You can change this to the desired amount
yourLabel.layer.masksToBounds = NO; //Keep this the same to avoid shadow being clipped by the label bounds
Hope this helps!
I have a rectangle image (jpg) and want to use it to fill the background of a button with rounded corner in xcode.
I wrote the following:
UIButton *button = [[UIButton buttonWithType:UIButtonTypeRoundedRect] retain];
CGRect frame = CGRectMake(x, y, cardWidth, cardHeight);
button.frame = frame;
[button setBackgroundImage:backImage forState:UIControlStateNormal];
However, the button I get with that approach doesn't have its corners rounded: it is instead a plain rectangle that looks exactly like my original image. How can I get instead an image with rounded corner to represent my button?
Thanks!
I tried the following solution with the UITextArea and I expect this will work with UIButton as well.
First of all import this in your .m file -
#import <QuartzCore/QuartzCore.h>
and then in your loadView method add following lines
yourButton.layer.cornerRadius = 10; // this value vary as per your desire
yourButton.clipsToBounds = YES;
You can achieve by this RunTime Attributes
we can make custom button.just see screenshot attached.
kindly pay attention :
in runtime attributes to change color of border follow this instruction
create category class of CALayer
in h file
#property(nonatomic, assign) UIColor* borderIBColor;
in m file:
-(void)setBorderIBColor:(UIColor*)color {
self.borderColor = color.CGColor;
}
-(UIColor*)borderIBColor {
return [UIColor colorWithCGColor:self.borderColor];
}
now onwards to set border color check screenshot
thanks
Pushing to the limits corner radius up to get a circle:
self.btnFoldButton.layer.cornerRadius = self.btnFoldButton.frame.height/2.0;
If button frame is an square it does not matter frame.height or frame.width. Otherwise use the largest of both ones.
You may want to check out my library called DCKit. It's written on the latest version of Swift.
You'd be able to make a rounded corner button/text field from the Interface builder directly:
It also has many other cool features, such as text fields with validation, controls with borders, dashed borders, circle and hairline views etc.
UIButton* closeBtn = [[UIButton alloc] initWithFrame:CGRectMake(10, 50, 90, 35)];
//Customise this button as you wish then
closeBtn.layer.cornerRadius = 10;
closeBtn.layer.masksToBounds = YES;//Important
Import QuartCore framework if it is not there in your existing project, then import #import <QuartzCore/QuartzCore.h> in viewcontroller.m
UIButton *button = [[UIButton buttonWithType:UIButtonTypeRoundedRect]];
CGRect frame = CGRectMake(x, y, width, height); // set values as per your requirement
button.layer.cornerRadius = 10;
button.clipsToBounds = YES;
First set width=100 and Height=100 of button
Objective C Solution
YourBtn1.layer.cornerRadius=YourBtn1.Frame.size.width/2;
YourBtn1.layer.borderColor=[uicolor blackColor].CGColor;
YourBtn1.layer.borderWidth=1.0f;
Swift 4 Solution
YourBtn1.layer.cornerRadius = YourBtn1.Frame.size.width/2
YourBtn1.layer.borderColor = UIColor.black.cgColor
YourBtn1.layer.borderWidth = 1.0
Try my code. Here you can set all properties of UIButton like text colour, background colour, corner radius, etc.
extension UIButton {
func btnCorner() {
layer.cornerRadius = 10
clipsToBounds = true
backgroundColor = .blue
}
}
Now call like this
yourBtnName.btnCorner()
For Objective C:
submitButton.layer.cornerRadius = 5;
submitButton.clipsToBounds = YES;
For Swift:
submitButton.layer.cornerRadius = 5
submitButton.clipsToBounds = true
If you want a rounded corner only to one corner or two corners, etc... read this post:
[ObjC] – UIButton with rounded corner - http://goo.gl/kfzvKP
It's a XIB/Storyboard subclass. Import and set borders without write code.
For Swift:
button.layer.cornerRadius = 10.0
updated for Swift 3 :
used below code to make UIButton corner round:
yourButtonOutletName.layer.cornerRadius = 0.3 *
yourButtonOutletName.frame.size.height
Swift 4 Update
I also tried many options still i wasn't able to get my UIButton round cornered.
I added the corner radius code inside the viewDidLayoutSubviews() Solved My issue.
func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
anyButton.layer.cornerRadius = anyButton.frame.height / 2
}
Also we can adjust the cornerRadius as follows:
func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
anyButton.layer.cornerRadius = 10 //Any suitable number as you prefer can be applied
}
An alternative answer which sets a border too (making it more like a button) is here ... How to set rectangle border for custom type UIButton
For iOS SWift 4
button.layer.cornerRadius = 25;
button.layer.masksToBounds = true;
You can use outlet connection and didSet function for your button on the view;
#IBOutlet weak var button: UIButton!{
didSet {
button.layer.cornerRadius = 5;
button.layer.masksToBounds = true;
}
}
How can I set label's border which is dynamically generated (Not from Interface Builder)?
you can do it by
Label.layer.borderColor = [UIColor whiteColor].CGColor;
Label.layer.borderWidth = 4.0;
before this you need to import a framework QuartzCore/QuartzCore.h
Swift version
Set label border
label.layer.borderWidth = 2.0
Set border color
label.layer.borderColor = UIColor.blueColor().CGColor
Use rounded corners
label.layer.cornerRadius = 8
Make background color stay within rounded corners
label.layer.masksToBounds = true
You can also try to subclass your label and override the drawRect: method to draw or a border or whatever you like:
- (void)drawRect:(CGRect)rect
{
[super drawRect:rect];
CGContextRef context = UIGraphicsGetCurrentContext();
[[UIColor blackColor] setStroke];
CGContextStrokeRect(context, self.bounds);
}
I'm not sure you can by default with UILabel. You might want to consider using a read-only (field.editing = NO) UITextField and setting it's borderStyle (which can be done programmatically using a UITextBorderStyle). That may be a little 'heavy' though. Another option may be to sub-class UILabel to draw your border.
Alternatively, and depending on your needs this may be better, use the backing CALayer and draw a border using it's borderColor and borderWidth properties.