1

我有一个很奇怪的问题。在一个视图中,我有三个按钮,每个按钮都有一个图像和一个标题。第一个按钮OK,第二个只显示一个图像,第三个显示正确的图像,但标题来自Button 2. 如下所示:

------------
I  Image 1 I
I  Title 1 I
------------

------------
I  Image 2 I
I          I
------------

------------
I  Image 3 I
I  Title 2 I
------------

我找不到是什么原因造成的。

我有一个 UIButton 子类,它有一个自定义的 init 方法,如下所示:

- (id)initWithFrame:(CGRect)frame withImage:(UIImage *)image andTitle:(NSString *)title
{

    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code
        self.backgroundColor = [UIColor clearColor];

        UIImageView *icon = [[UIImageView alloc] initWithImage:image];
        icon.backgroundColor = [UIColor clearColor];
        CGRect iconFrame = icon.frame;
        iconFrame.origin.x = frame.size.width / 2 - iconFrame.size.width / 2;
        iconFrame.origin.y = 5;
        iconFrame.size.height = frame.size.height / 2.5;
        icon.frame = iconFrame;

        [self addSubview:icon];

        UILabel *titleLabel = [[UILabel alloc] initWithFrame:frame];
        titleLabel.textAlignment = NSTextAlignmentCenter;
        titleLabel.font = [UIFont fontWithName:@"TisaMobiPro" size:14];
        [titleLabel setText:title];
        titleLabel.textColor = [UIColor colorWithRed:1.000 green:1.000 blue:1.000 alpha:0.5];
        titleLabel.backgroundColor = [UIColor clearColor];

        CGRect titleFrame = titleLabel.frame;
        titleFrame.origin.y = icon.frame.origin.y + icon.frame.size.height;
        titleFrame.size.height = frame.size.height / 2;
        titleLabel.frame = titleFrame;
        [self addSubview:titleLabel];
    }
    return self;
}

我添加这样的按钮:

int numberOfButtons = 3;

CGRect mentionRect = CGRectMake(0, 10,self.menuContainer.frame.size.width / numberOfButtons, self.menuContainer.frame.size.height - 10);
self.mentionButton = [[CustomBarButton alloc] initWithFrame:mentionRect withImage:[UIImage imageNamed:@"Images/Mentions.png"] andTitle:@"Mention"];
[self.menuContainer addSubview:self.mentionButton];


CGRect hashRect = CGRectMake(mentionRect.origin.x + mentionRect.size.width, 10,self.menuContainer.frame.size.width / numberOfButtons, self.menuContainer.frame.size.height - 10);
self.hashtagButton = [[CustomBarButton alloc] initWithFrame:hashRect withImage:[UIImage imageNamed:@"Images/HashTagIcon.png"] andTitle:@"Hashtag"];
[self.menuContainer addSubview:self.hashtagButton];


CGRect photoRect = CGRectMake(hashRect.origin.x + hashRect.size.width, 10, self.menuContainer.frame.size.width / numberOfButtons, self.menuContainer.frame.size.height - 10);
self.photoButton = [[CustomBarButton alloc] initWithFrame:photoRect withImage:[UIImage imageNamed:@"Images/CameraIcon.png"] andTitle:@"Photo"];
[self.menuContainer addSubview:self.photoButton];

谁能找到造成这种情况的原因,或者对我能做些什么来解决它有任何想法?

4

1 回答 1

1

检查框架设置UILabel *titleLabel = [[UILabel alloc] initWithFrame:frame];。您不应将 frame 设置为frameinit 方法中的输入参数。尝试设置一个静态框架,然后根据您的要求进行修改,以将其放置在该视图中您需要的任何位置。基本上你的origin.x价值出了问题,这就是为什么你得到奇怪的输出。

于 2013-03-03T11:36:24.647 回答