Dotted / Dashed border for UITextView / UITextField

本秂侑毒 提交于 2019-12-07 05:19:40

问题


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.


回答1:


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.




回答2:


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. :)




回答3:


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


来源:https://stackoverflow.com/questions/10813146/dotted-dashed-border-for-uitextview-uitextfield

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!