用另一个视图IOS包装标签

时间:2016-06-08 15:39:41

标签: ios user-interface ios-autolayout

我想在带有圆角的黑色矩形上创建一个标签,并在标签的边框和矩形的边框之间添加一些填充。如果在运行时文本长度发生变化,还必须正确包装标签。

外观应该是这样的观点:

enter image description here

但内置于我的视图内而非浮动。

我没有iOS界面构建器的经验,我该如何实现?

3 个答案:

答案 0 :(得分:1)

最简单的方法是

创建一个黑色背景颜色的简单UILabel并设置其角半径。您可以将此标签放在任何您想要的位置。

答案 1 :(得分:1)

据我所知,您希望显示一个弹出窗口,以显示一些动态的文本,只需传递文本即可显示在任何地方。

您需要做的是创建一个自定义视图,其中包含带有顶部,底部,前导和尾随约束的标签,其大小将根据文本增加。使用参数descriptionText:NSStringonViewController:UIViewController创建一个类方法。在里面根据文本设置customView的框架。

如果您想让尺寸动态,可以使用以下代码: -

-(CGSize)getLabelSizeFortext:(NSString *)text forWidth:(float)width WithFont:(UIFont *)font
{
    CGSize constraint = CGSizeMake(width, MAXFLOAT);
    CGRect titleRect = [text boundingRectWithSize:constraint options:(NSStringDrawingUsesLineFragmentOrigin| NSStringDrawingTruncatesLastVisibleLine) attributes:@{NSFontAttributeName:font} context:nil];
    return titleRect.size;
}

在您的类方法中,将您的customView添加到currentViewController

onViewController.view.addSubView(self)

如果需要,可以为其设置动画,并在几秒钟后让它消失,以便用户能够阅读文本。就外观而言,将backgroundColor设置为[UIColor blackColor],将alpha设置为8.0。

答案 2 :(得分:0)

你可能只用一个标签就可以逃脱。

如果您没有为标签指定特定宽度,它将根据文本的长度调整自身大小。

您可以在“属性”选项卡的“查看”部分下的Interface Builder中更改标签的背景颜色和不透明度。

圆角需要在代码中完成,方法是更改​​标签CALayer(import UIKit class TableViewController: UITableViewController { var array = ["first", "second", "third"] override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return array.count } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) let text = array[indexPath.row] let result: String switch text { case "first": result = "works" case "second": result = "works also" case "third": result = "what a surprise, works also" default: result = "doesn't work" } cell.textLabel?.text = text cell.detailTextLabel?.text = result return cell } } )的圆角半径。您可以通过在Interface Builder中添加用户定义的运行时属性来更改角点,但我还没有尝试过,所以我无法肯定地说出我的想法。

相关问题