我想在一个UITextView
周围加上细灰色的边框。我已经查阅了苹果的文档,但未能找到任何属性。请帮忙。
#import <QuartzCore/QuartzCore.h>
....
// typically inside of the -(void) viewDidLoad method
self.yourUITextView.layer.borderWidth = 5.0f;
self.yourUITextView.layer.borderColor = [[UIColor grayColor] CGColor];
添加以下代码以实现圆角效果:
self.yourUITextview.layer.cornerRadius = 8;
这是我使用的代码,为我的名为"tbComments"的TextView
控件添加边框:
self.tbComments.layer.borderColor = [[UIColor grayColor] CGColor];
self.tbComments.layer.borderWidth = 1.0;
self.tbComments.layer.cornerRadius = 8;
以下是它的外观:
非常简单。
UIImageView
作为UITextView
的子视图添加。这与UITextField
上的原生边界匹配,包括从上到下的渐变:textView.backgroundColor = [UIColor clearColor];
UIImageView *borderView = [[UIImageView alloc] initWithFrame: CGRectMake(0, 0, textView.frame.size.width, textView.frame.size.height)];
borderView.autoresizingMask = UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth;
UIImage *textFieldImage = [[UIImage imageNamed:@"TextField.png"] resizableImageWithCapInsets:UIEdgeInsetsMake(15, 8, 15, 8)];
borderView.image = textFieldImage;
[textField addSubview: borderView];
[textField sendSubviewToBack: borderView];
这些是我使用的 PNG 图像,以及一个 JPG 表示:
code
代码最佳:
resizableImageWithCapInsets:UIEdgeInsetsMake(28, 14, 28, 14)
- RefuX代码工作的很好,但颜色应该是CGColor
而不是UIColor
:
view.layer.borderWidth = 5.0f;
view.layer.borderColor = [[UIColor grayColor] CGColor];
我相信以上答案适用于早期版本的Swift。我进行了一些谷歌搜索,以下代码可用于Swift 4。只是分享给可能有用的人。
self.textViewName.layer.borderColor = UIColor.lightGray.cgColor
self.textViewName.layer.borderWidth = 1.0
self.textViewName.layer.cornerRadius = 8
愉快编码!
self.textViewName.layer.borderColor = UIColor.systemGray4.cgColor
。 - multitudes对于Swift编程,请使用以下内容
tv_comment.layer.borderWidth = 2
tv_comment.layer.borderColor = UIColor(red: 0.2, green: 0.2, blue: 0.2, alpha: 1).CGColor
UIColor(white: 0.2, alpha: 1).CGColor
。 - Leo这是我能接近原始UITextField的程度
func updateBodyTextViewUI() {
let borderColor = UIColor.init(red: 212/255, green: 212/255, blue: 212/255, alpha: 0.5)
self.bodyTextView.layer.borderColor = borderColor.CGColor
self.bodyTextView.layer.borderWidth = 0.8
self.bodyTextView.layer.cornerRadius = 5
}
从iOS 8和Xcode 6开始,我现在发现最好的解决方案是子类化UITextView并将子类标记为IB_DESIGNABLE,这将允许您在Storyboard中查看边框。
标题:
#import <UIKit/UIKit.h>
IB_DESIGNABLE
@interface BorderTextView : UITextView
@end
实现:
#import "BorderTextView.h"
@implementation BorderTextView
- (void)drawRect:(CGRect)rect
{
self.layer.borderWidth = 1.0;
self.layer.borderColor = [UIColor blackColor].CGColor;
self.layer.cornerRadius = 5.0f;
}
@end
然后在Storyboard中拖出UITextView,并将其类设置为BorderTextView
self.myView.layer.borderWidth ...
这样做,但正如我所说,图层是只读的,因此图层没有任何可用于设置的方法或变量。 - Paulius Vindzigelskis