ios - 如何以编程方式将 UIView(或更具体地说,UITextAreas)嵌入到文本中?

标签 ios iphone objective-c uiview uitextfield

出于可重用性的原因,我有兴趣找到一种方法,以高效的方式以编程方式将文本和自定义 UITextFields 添加到 View ,类似于您可以使用 NSString 的 stringWithFormat: 组合字符串,然后将结果分配给 UILabel 的方式文本属性。理想情况下,使用 2-3 条语句,我可以编写文本并将我的 UITextField 对象包含在一个字符串中,并获得一个自动文本换行、格式良好的 UIView,我可以将其直接嵌入到我的 View 中。基本上,它的功能类似于具有添加 UIView 对象的能力的 UILabel。对于输出的示例,此图像将是文本和带下划线的 UITextFields 的组合:

enter image description here 如果存在,它将允许我重用单个 UITableViewCell 子类,而不是拥有 5-6 个 xib 和 3-4 个子类。我已经搜索了大约 2 个小时,但没有真正找到一个预先存在的解决方案,所以有没有人以前遇到过这个问题并使用或发布了一个库来处理这个问题,或者是否有一个我忽略的简单解决方案?

谢谢!

最佳答案

您可以使用 CSLinearLayoutView ( https://github.com/scalessec/CSLinearLayoutView ) 并创建一个类

@implementation LabledView

+ (UIView*)create :(CGRect) frame view:(UIView*) view labelTitle:(NSString*)labelTitle viewLinearLayoutMakePadding :(CSLinearLayoutItemPadding)viewLinearLayoutMakePadding labelLinearLayoutMakePadding :(CSLinearLayoutItemPadding)labelLinearLayoutMakePadding font:(UIFont*)font textColor:(UIColor*)textColor
{
    CSLinearLayoutView *container = [[CSLinearLayoutView alloc] initWithFrame:frame];
    container.orientation = CSLinearLayoutViewOrientationHorizontal;

    UILabel *label = [[UILabel alloc] init];
    label.textColor = textColor;
    [label setText:labelTitle];
    [label setFont:font];
    [label sizeToFit];

    CSLinearLayoutItem *itemLabel = [CSLinearLayoutItem layoutItemForView:label];
    itemLabel.padding = labelLinearLayoutMakePadding;

    CSLinearLayoutItem *itemView = [CSLinearLayoutItem layoutItemForView:view];
    itemView.padding = viewLinearLayoutMakePadding;

    [container addItem:itemLabel];
    [container addItem:itemView];
    return container;
}

例子:

UITextField *textField = [[UITextField alloc] initWithFrame:CGRectMake(0, 0, 260, 40)];

UIView *customView = [LabledView create:CGRectMake(0, 0, 280, 40) view:textField 
labelTitle:@"your label" viewLinearLayoutMakePadding:CSLinearLayoutMakePadding(0, 10, 0, 0) 
labelLinearLayoutMakePadding:CSLinearLayoutMakePadding(10, 0, 0, 0)
 font:[UIFont fontWithName:@"Helvetica" size:12] textColor:[UIColor blackColor]];

关于ios - 如何以编程方式将 UIView(或更具体地说,UITextAreas)嵌入到文本中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22021999/

相关文章:

iphone - 如何将没有标签栏的普通 UIViewController 转换为有标签栏的 UIViewController

ios - UITableView cellForRowAtIndexPath : How to return no cell

ios - SCNNodes 中的颜色

iPhone 4s 6.1.2 版 UIViewcontroller 在使用相机拍照时刷新

ios - 更新到版本 3.0.2 后,地方自动完成功能不起作用 - Google iOS sdk

iphone - 从不兼容的指针类型传递 ObjectForKey 的参数

iphone - 刷新CoreData表?

objective-c - 在 NSOutlineView 中为 "sliding"设置动画

ios - 动态创建 NSMutableArray,并在对象上使用带参数的选择器

ios - 具有自动布局的 UIView 最小和最大高度