如何在 iPhone 上创建圆角 UILabel? [英] How do I create a round cornered UILabel on the iPhone?

查看:20
本文介绍了如何在 iPhone 上创建圆角 UILabel?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有内置的方法来创建圆角 UILabels?如果答案是否定的,人们将如何创建这样一个对象?

Is there a built in way to create round-cornered UILabels? If the answer is no, how would one go about creating such an object?

推荐答案

iOS 3.0 及更高版本

iPhone OS 3.0 及更高版本支持 CALayer 类上的 cornerRadius 属性.每个视图都有一个您可以操作的 CALayer 实例.这意味着您可以在一行中获得圆角:

iOS 3.0 and later

iPhone OS 3.0 and later supports the cornerRadius property on the CALayer class. Every view has a CALayer instance that you can manipulate. This means you can get rounded corners in one line:

view.layer.cornerRadius = 8;

您需要 #import 并链接到 QuartzCore 框架以访问 CALayer 的标头和属性.

You will need to #import <QuartzCore/QuartzCore.h> and link to the QuartzCore framework to get access to CALayer's headers and properties.

我最近使用的一种方法是创建一个 UIView 子类,它只是绘制一个圆角矩形,然后制作 UILabel 或者在我的情况下,UITextView,它内部的一个子视图.具体:

One way to do it, which I used recently, is to create a UIView subclass which simply draws a rounded rectangle, and then make the UILabel or, in my case, UITextView, a subview inside of it. Specifically:

  1. 创建一个 UIView 子类并将其命名为 RoundRectView.
  2. RoundRectViewdrawRect: 方法中,使用 Core Graphics 调用(如 CGContextAddLineToPoint() 为边缘和 CGContextAddArcToPoint() 绘制围绕视图边界的路径)用于圆角.
  3. 创建一个 UILabel 实例并使其成为 RoundRectView 的子视图.
  4. 将标签的框架设置为 RoundRectView 边界的几个像素内嵌.(例如,label.frame = CGRectInset(roundRectView.bounds, 8, 8);)
  1. Create a UIView subclass and name it something like RoundRectView.
  2. In RoundRectView's drawRect: method, draw a path around the bounds of the view using Core Graphics calls like CGContextAddLineToPoint() for the edges and and CGContextAddArcToPoint() for the rounded corners.
  3. Create a UILabel instance and make it a subview of the RoundRectView.
  4. Set the frame of the label to be a few pixels inset of the RoundRectView's bounds. (For example, label.frame = CGRectInset(roundRectView.bounds, 8, 8);)

如果您创建通用 UIView,然后使用检查器更改其类,则可以使用 Interface Builder 将 RoundRectView 放置在视图上.在编译和运行应用程序之前,您不会看到矩形,但至少您可以放置​​子视图并将其连接到出口或操作(如果需要).

You can place the RoundRectView on a view using Interface Builder if you create a generic UIView and then change its class using the inspector. You won't see the rectangle until you compile and run your app, but at least you'll be able to place the subview and connect it to outlets or actions if needed.

这篇关于如何在 iPhone 上创建圆角 UILabel?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆