簡體   English   中英

如何垂直對齊在UITextField中用作leftView的UILabel與textField的文本?

[英]How to vertically align a UILabel used as a leftView in a UITextField with the textField's text?

我使用UILabel作為UITextFieldleftView 問題是textField的文本高於標簽的文本。

這是我到目前為止使用的代碼

UILabel *startsWith = [[UILabel alloc] init];
startsWith.font = [UIFont systemFontOfSize:14];
startsWith.textColor = [UIColor blackColor];
startsWith.backgroundColor = [UIColor clearColor];
startsWith.text = @"Text";
[startsWith sizeToFit];
self.textField.leftViewMode = UITextFieldViewModeAlways;
self.textField.leftView = startsWith;

我試過稍微改變標簽的框架,但是沒有用...

如何對齊兩個文本?

您可以創建一個容器視圖,在其中將UILabel向上放置1px。

    UIView * v = [[UIView alloc] init];
    v.backgroundColor = [UIColor clearColor];

    UILabel *startsWith = [[UILabel alloc] init];
    startsWith.font = self.textfield.font;
    startsWith.textAlignment = self.textfield.textAlignment;
    startsWith.textColor = [UIColor blackColor];
    startsWith.backgroundColor = [UIColor clearColor];
    startsWith.text = @"Text";
    [startsWith sizeToFit];

    startsWith.frame = CGRectOffset(startsWith.frame, 0, -1);
    v.frame = startsWith.frame;
    [v addSubview:startsWith];
    self.textfield.leftViewMode = UITextFieldViewModeAlways;
    self.textfield.leftView = v;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM