有边框的 UITextView
我想在 UITextView
周围有一个灰色的细边框。我已经浏览了苹果文档,但找不到任何属性。请帮忙。
I want to have a thin gray border around a UITextView
. I have gone through the Apple documentation but couldn't find any property there. Please help.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(15)
我添加
UIImageView
作为UITextView
的子视图。这与UITextField
上的原生边框相匹配,包括从上到下的渐变:这些是我使用的 png 图像和 jpg 表示形式:
@1x
@2x
I add
UIImageView
as a subview of theUITextView
. This matches the native border on aUITextField
, including the gradient from top to bottom:These are the png images I use, and a jpg representation:
@1x
@2x
效果很好,但颜色应该是
CGColor
,而不是UIColor
:Works great, but the color should be a
CGColor
, notUIColor
:我相信以上答案适用于 Swift 的早期版本。我在 Google 上搜索了一下,下面的代码适用于 Swift 4。只是将其分享给可能受益的人。
快乐编码!
I believe the above answers are for the previous versions of Swift. I Googled a bit and the below code works for Swift 4. Just sharing it for whoever it may benefit.
Happy Coding!
对于 Swift 编程,请使用这个
for Swift Programming, use this
这与原始 UITextField 尽可能接近
this is as close as I could from an original UITextField
您可以从故事板 - 身份检查器 - 用户定义的运行时属性
you can add border to UITextView from the Storyboard - Identity Inspector - User Defined Runtime Attribute
从 iOS 8 和 Xcode 6 开始,我现在发现最好的解决方案是子类化 UITextView 并将子类标记为 IB_DESIGNABLE,这将允许您在 Storyboard 中查看边框。
标题:
实现:
然后只需在故事板中拖出 UITextView 并将其类设置为 BorderTextView
As of iOS 8 and Xcode 6, I now find the best solution is to subclass UITextView and mark the subclass as an IB_DESIGNABLE, which will allow you to view the border in storyboard.
Header:
Implementation:
Then just drag out your UITextView in storyboard and set its class to BorderTextView
使它起作用的事情(除了遵循此处的答案之外)是添加
borderStyle
属性:The thing that made it work (in addition to following the answers here) is adding the
borderStyle
attribute:只是一个小小的补充。如果将边框设置得更宽一些,则会干扰文本的左侧和右侧。为了避免这种情况,我添加了以下行:
Just a small addition. If you make the border a bit wider, it will interfere with the left and right side of text. To avoid that, I added the following line:
在 Swift 3 中,您可以使用以下两行:
In Swift 3, you may use the following two lines:
一个优雅的解决方案是在底部插入一个真正的 UITextField 并防止它随内容滚动。这样你就可以拥有正确的深色模式边框。
An elegant solution would be to insert a real UITextField on the bottom and prevent it to scroll with the content. This way you have even the correct dark mode borders. ????
我通过在
UITextView
后面放置一个完全禁用的UIButton
并将UITextView
的背景颜色设置为clearColor,在情节提要中解决了这个问题。这不需要额外的代码或包就可以工作。I solved this problem in storyboard by putting a fully disabled
UIButton
behind theUITextView
and making the background color of theUITextView
clearColor. This works without requiring extra code or packages.为圆角添加以下内容:
Add the following for rounded corners:
这是我使用的代码,用于在名为“tbComments”的
TextView
控件周围添加边框:如下所示:
简单易行。
Here's the code I used, to add a border around my
TextView
control named "tbComments" :And here's what it looks like:
Easy peasy.