我在UIButton中添加了UIView

    UIButton *switchButtonL = [UIButton buttonWithType: UIButtonTypeSystem];
    [switchButtonL addTarget:self action:@selector(switchCity:) forControlEvents:UIControlEventTouchUpInside];
    switchButtonL.frame =  CGRectMake(0, 50, self.screenWidth/2, 30);
    [switchButtonL setTitle: NSLocalizedString(@"switchcity", nil) forState:UIControlStateNormal];
    [switchButtonL setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [switchButtonL setTitleColor:[UIColor blueColor] forState:UIControlStateSelected];
    [switchButtonL setBackgroundColor:[UIColor clearColor] ];
    switchButtonL.titleLabel.textAlignment = NSTextAlignmentLeft; // this line can't work
    switchButtonL.titleLabel.font = [UIFont fontWithName:@"HelveticaNeue-Light" size:18];
    [self addSubview:switchButtonL];


并且注释行不起作用,文本始终居中对齐。

最佳答案

尝试替代

switchButtonL.titleLabel.textAlignment = NSTextAlignmentLeft; // this line can't work


拥有:

switchButtonL.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
switchButtonL.contentEdgeInsets = UIEdgeInsetsMake(0, 10, 0, 0);

关于ios - iOS从代码中添加UIButton:无法控制UIButton标题栏文本对齐,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/24507868/

10-11 17:37