IOS15UIButton根据文字长度计算宽高
自定义一个UIButton,如何不设置它的宽高,让其根据自身文字的多少,自动设置自身大小呢,
主要使用ios7推出的boundingRectWithSize方法.最后把文字的宽度加上图片的宽度,加上文字的偏移值。
- (void)layoutSubviews{
[super layoutSubviews];
NSDictionary *attrs = @{
NSFontAttributeName: self.titleLabel.font
};
CGFloat titleW = [self.title boundingRectWithSize:CGSizeMake(MAXFLOAT,MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin attributes:attrs context:nil].size.width;
self.hm_width = titleW + self.titleEdgeInsets.left + self.currentImage.size.width;
}
@end
Xnip2021-11-29_14-36-35.jpg
swift5写法
//
// TitleButton.swift
// testLabelSwift
//
// Created by lujun on 2021/11/29.
//
import UIKit
class TitleButton: UIButton {
var titleStr: String? {
didSet {
guard let titleStr = titleStr else {
return
}
self.setTitle(titleStr, for: .normal)
}
}
override init(frame: CGRect) {
super.init(frame: frame)
self.isUserInteractionEnabled = false
self.setImage(UIImage(named:"navbar_netease"), for: .normal)
self.titleLabel?.font = UIFont.systemFont(ofSize: 22)
self.titleEdgeInsets = UIEdgeInsets(top: 0, left: 8, bottom: 0, right: 0)
self.frame.size.height = CGFloat(self.currentImage!.size.height)
self.setTitleColor(.white, for: .normal)
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func layoutSubviews() {
super.layoutSubviews()
let dict = [NSAttributedString.Key.font : self.titleLabel?.font]
let titleW = (titleStr! as NSString).boundingRect(with: CGSize(width: LONG_MAX, height: LONG_MAX), options: .usesLineFragmentOrigin, attributes: dict as [NSAttributedString.Key : Any], context: nil).size.width
let imageW = self.currentImage?.size.width
self.frame = CGRect(x: 0, y: 0, width: titleW + self.titleEdgeInsets.left + (imageW ?? 0), height: 30)
}
}