如何根据字符串长度获取CGFloat / CGSize?

时间:2017-10-11 11:03:34

标签: ios swift cgfloat cgsize

我有一个UIView,它充当容器,并且此容器的宽度需要根据最长的String动态更改。所以我想根据字符串长度得到CGFloat / CGSize,还可以吗?

现在看来最有帮助的方法已经折旧......

myStringSize : CGSize  = [longestString sizeWithFont:myFont 
                       constrainedToSize:maximumSize 
                       lineBreakMode:self.myLabel.lineBreakMode];

我希望将其基于String

,而不是将其基于标签

3 个答案:

答案 0 :(得分:0)

你必须给出已知宽度或高度:

extension String {

    func getHeight(with width: CGFloat, font: UIFont) -> CGFloat {
        let maxSize = CGSize(width: width, height: CGFloat.greatestFiniteMagnitude)
        let actualSize = self.boundingRect(with: maxSize, options: [.usesLineFragmentOrigin], attributes: [NSFontAttributeName: font], context: nil)
        return actualSize.height
    }


    func getWidth(with height: CGFloat, font: UIFont) -> CGFloat {
        let maxSize = CGSize(width: CGFloat.greatestFiniteMagnitude, height: height)
        let actualSize = self.boundingRect(with: maxSize, options: [.usesLineFragmentOrigin], attributes: [NSFontAttributeName: font], context: nil)
        return actualSize.width
    }
}

答案 1 :(得分:0)

1 - 首先定义您想要的最大尺寸MaxWidth

 CGSize constraint = CGSizeMake(MaxWidth, CGFLOAT_MAX);

text的2-属性:

NSDictionary *attributes = [NSDictionary dictionaryWithObjectsAndKeys: [UIFont systemFontOfSize:FONT_SIZE], NSFontAttributeName, nil];

3- *这是如何从paraRect发送text

CGRect paraRect = [text boundingRectWithSize:constraint options:(NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeading) attributes:attributes context:nil];

4- *最后得到尺寸:

CGSize size = paraRect.size;

答案 2 :(得分:0)

感谢您的帮助@Venkat,这是适合我的解决方案

 @objc func containerWidth() -> (CGFloat){
        let containerSize = self.myLabel.intrinsicContentSize
        containerWidth = containerSize.width
        return containerWidth
    }