在UIPopoverController中显示UITableViewController,可变宽度

时间:2013-01-30 22:21:22

标签: ios objective-c uitableview uipopovercontroller

我将使用UIPopoverController来显示UITableViewController。表格视图将显示一个长度不明的名字列表(可能是鲍勃或可能是亚历山大)。

我知道如何改变弹出窗口的高度,但我似乎无法计算如何改变它的宽度,因此名称不会被截断。

需要弄清楚名称的宽度,以便我可以将popover设置为该宽度,这样名称就不会从popover中流出:

enter image description here

任何想法?

2 个答案:

答案 0 :(得分:1)

获取字符串的宽度,然后将UITable设置为该宽度。这是一个可以添加以获得宽度的方法。您可以将其添加到类别或类中。我从here获取了代码。

- (CGFloat)widthOfString:(NSString *)string withFont:(NSFont *)font {
     NSDictionary *attributes = [NSDictionary dictionaryWithObjectsAndKeys:font, NSFontAttributeName, nil];
     return [[[NSAttributedString alloc] initWithString:string attributes:attributes] size].width;
 }

通过这种方式,您可以指定正在使用的字体,以防将来更改它。 (不同的字体显然会产生不同的宽度)。

答案 1 :(得分:0)

据推测,你有一系列的名字。您要做的是枚举名称列表,确定每个名称所需的长度,然后存储最大的名称并将其应用为所需的宽度。您需要定义不应超过的“最大大小”。沿着这些方向的方法应该返回一些合适的方法:

- (CGFloat)suitableWidthForLabel:(UILabel *)nameLabel withNames:(NSArray *)arrayOfNames
{

    CGFloat suitableWidth = 100.0f; // A reasonable starting point
    CGSize maximumSize = CGSizeMake(600.0f, nameLabel.frame.size.height);
    UIFont *labelFont = [nameLabel font];

    for (NSString *aName in arrayOfNames)
    {

        CGSize expectedLabelSize = [aName sizeWithFont:labelFont
                                        constrainedToSize:maximumSize
                                            lineBreakMode:nameLabel.lineBreakMode];

        suitableWidth = MAX(suitableWidth, expectedLabelSize.width);
    }

    return suitableWidth; // This will be the largest size you may need to accommodate
}