ios - 仅在 uilabel 周围绘制顶部、右侧和底部边框

标签 ios uilabel

我尝试为 uilabel 添加边框,但我只想有 top、right 和 bottom 边框。

像这样

           ----------------
                          |
            I am a label  |
                          |
           ----------------

我尝试使用这些代码,但它默认添加了所有 4 个面

    myLabel.layer.borderWidth = 1;
    myLabel.layer.borderColor = [UIColor blackColor];

无论如何我只能添加 3 个边,甚至是 1 个或 2 个边?

谢谢!

最佳答案

你可以使用面具。这是我用来测试理论的代码,效果很好:

// Define the border width in a variable, we'll be using it elsewhere
CGFloat borderWidth = 1.0;

// This creates a testing view to test the theory, in your case this will be your UILabel
UIView* view = [[UIView alloc] initWithFrame:CGRectMake(20, 60, 250, 100)];
view.layer.borderColor = [UIColor blackColor].CGColor;
view.layer.borderWidth = borderWidth;
[self.view addSubview:view];

// Create the mask to cover the area of the view you want to **show**
// Here, we create a mask that covers most of the view, except the left edge
// The mask needs to be coloured in black, as black acts as transparent, whereas white is opaque in mask parlance
UIView* mask = [[UIView alloc] initWithFrame:CGRectMake(borderWidth, 0, view.frame.size.width - borderWidth, view.frame.size.height)];
mask.backgroundColor = [UIColor blackColor];
view.layer.mask = mask.layer;

您可以调整 mask 的大小和位置(给定 borderWidth)以显示/隐藏您感兴趣的边框边缘。上面的示例隐藏了左边缘。

关于ios - 仅在 uilabel 周围绘制顶部、右侧和底部边框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21586089/

相关文章:

iphone - 将文本输入从一个 View 放到另一个 View

swift - 将多个 pickerView 选定值导出到 UILabel 上的数字

ios - 给定带有多行标签的 Collection View 单元格的宽度,如何获得首选的 AutoLayout 高度?

ios - 如何以编程方式将 View 设置为正面/背面?

ios - 在 iOS 中解析字符串

php - IOS SWIFT 2 - Http 将 json 数组发布到服务器

ios - 是否可以使用 ObjectMapper 创建 JSON?

ios - 使用 Setter 和 Getter 方法与直接操作相比的好处

ios - 如何在导航栏中设置多行大标题? ( iOS 11 的新功能)

iphone - 将 UILabel 中的单词居中的算法