【问题标题】:iOS Calc X position to place elements on a ViewiOS Calc X 将元素放置在视图上的位置
【发布时间】:2014-07-12 14:59:00
【问题描述】:

我想在我的NavigationItemtitleView 中添加标签和图像。我将UILabelUIImageView 添加到UIView 并将其设置为导航项的titleView。正在添加东西,但我无法计算标签的长度并将图像放在它旁边。 我的代码是:-

// Title Name + Image
UIView *titView = [[UIView alloc] initWithFrame:self.navigationItem.titleView.bounds];
self.navigationItem.titleView = titView;

UILabel *title = [[UILabel alloc] initWithFrame:CGRectMake(-10, -20, 150, 30)];
title.text = @"Bunny ";
[title setTextColor:[UIColor orangeColor]];
[titView addSubview:title];

float x2 = 30;     //+ title.bounds.size.width;
UIImageView *img = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"return" ]];
img.frame = CGRectMake(x2, -20, img.bounds.size.width, 30);

[titView addSubview:img];

我正在寻找一些方法来计算宽度文本并相应地设置标签的宽度。现在我将标签的宽度设置为 150。其次,计算 x 位置以将图像放在标签旁边。

尝试了很多方法,但都没有按预期工作。我怎样才能做到这一点?你能不能给出一些指导方针,这样无论标签文本的长度如何,事情都会按预期工作,并且 UIView 被放置在导航项的中心。

非常感谢任何帮助。谢谢。

【问题讨论】:

  • 您应该使用布局约束来执行此操作,并在图像视图和标签之间设置水平间距约束。您不需要设置标签的宽度,它会根据字符串自行调整大小。

标签: ios objective-c uiview position


【解决方案1】:

你可以打电话

[title sizeToFit]; 

在设置其属性后,它会自行调整大小以匹配所包含的字符串。

将 imageViews x 原点设置为

CGRectGetMaxX(title.frame) + desiredSpacing;

它可以帮助子类化UIView 以通过覆盖layoutSubviews 并将您的视图放在那里来实现最终结果,因为titleView 的框架可以通过navigationBar 调整......基本上像这样:

@implementation TitleView{
    UILabel *_titleLabel;
    UIImageView *_img;
}

- (id)initWithTitle:(NSString *)title andImage:(UIImage *)image
{
    self = [super init];
    if (self) {

        _titleLabel = [[UILabel alloc] init];
        _titleLabel.text = title;
        [_titleLabel setTextColor:[UIColor orangeColor]];
        [_titleLabel sizeToFit];
        [self addSubview:_titleLabel];

        _img = [[UIImageView alloc] initWithImage:image];
        [self addSubview:_img];
    }    
    return self;
}

- (void)layoutSubviews{
    CGFloat spacingBetweenTextAndImage = 0;
    CGFloat width = CGRectGetWidth(_titleLabel.frame)+CGRectGetWidth(_img.frame)+spacingBetweenTextAndImage;

    CGFloat x = (CGRectGetWidth(self.bounds)-width)/2;
    _titleLabel.frame = CGRectMake(x, (CGRectGetHeight(self.bounds)-CGRectGetHeight(_titleLabel.bounds))/2, CGRectGetWidth(_titleLabel.bounds), CGRectGetHeight(_titleLabel.bounds));

    x+=CGRectGetWidth(_titleLabel.bounds)+spacingBetweenTextAndImage;

    _img.frame = CGRectMake(x, (CGRectGetHeight(self.bounds)-CGRectGetHeight(_img.bounds))/2, CGRectGetWidth(_img.bounds), CGRectGetHeight(_img.bounds));
}
@end

在你的 viewController 中使用:

UIView *titleView = [[TitleView alloc] initWithTitle:@"Bunny" andImage:[UIImage imageNamed:@"return" ]];
self.navigationItem.titleView = titleView;

【讨论】:

    猜你喜欢
    • 2011-12-31
    • 1970-01-01
    • 2013-07-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-04
    相关资源
    最近更新 更多