2014-02-25 23 views
1

由於可重用性的原因,我有興趣找到一種以有效的方式以編程方式向視圖添加文本和自定義UITextField的方法,類似於如何使用NSString的stringWithFormat組合字符串:然後將結果分配給UILabel的文本屬性。理想情況下,使用2-3條語句可以編寫文本,並將我的UITextField對象包含在一個字符串中,並獲得一個自動文本包裝的,格式良好的UIView,我可以直接將其嵌入到視圖中。基本上,它將像UILabel一樣具有添加UIView對象的功能。對於輸出的一個例子這個圖像將是文本和下劃線UITextFields的組合:如何以編程方式嵌入UIViews(或更具體地說,UITextAreas)?

enter image description here 如果存在,它會允許我重用單個的UITableViewCell子類,而不是具有5-6 xibs和3-4子類。我已經搜索了大約2個小時,但沒有真正的運氣來預先存在的解決方案,所以有人曾經遇到過這個問題,並使用或發佈了一個庫來處理這個問題,還是有一個我忽略的簡單解決方案?

謝謝!

回答

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]]; 
+0

幾乎正是我所期待的!唯一能讓這個庫變得更好的東西是,如果能夠在兩行之間自動包裝字符串,但是當你將對象引入混合時會變得相當複雜。我會通過使用表示線條的數組進行補償。謝謝! – jonschneider

0

你可以強調,對於NSAtttibutedString字符串的具體範圍。您可以在ios6中將A分佈的字符串設置爲UILabel ...所以這就是我要做的方式,那麼它確實可以放在單個標籤中,只需要下劃線(或不同的字體/顏色/等)。在查看屬性字符串時要小心,它屬性字典使用與UIKit(這裏是您需要的那些)的不同鍵來使用CoreText。

+0

我花了很多時間查看NSAttributedString,看看我是否可以使用和/或修改它來做我想做的事情,因爲它可以自動處理格式並根據字符範圍觸發選擇器。我發現如果我使用NSAttributedString,我可以做下劃線,但是我不能將交互式UITextFields添加到文本中,而且這將是一個過度的,非常乾的努力來複制我需要從UITextField手動。 – jonschneider

相關問題