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

陌路散爱 提交于 2019-12-07 07:07:16

问题


I'm using a UILabel as the leftView of a UITextField. The issue is that the textField's text is higher than the label's.

This is the code I've used so far

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;

I've tried slightly changing the label's frame but it didn't work...

How can I align both texts?


回答1:


You could create a container view in which you position the UILabel 1px up.

    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;


来源:https://stackoverflow.com/questions/11332782/how-to-vertically-align-a-uilabel-used-as-a-leftview-in-a-uitextfield-with-the-t

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!