IOS15UIButton根據(jù)文字長(zhǎng)度計(jì)算寬高
自定義一個(gè)UIButton仔涩,如何不設(shè)置它的寬高姑曙,讓其根據(jù)自身文字的多少聘芜,自動(dòng)設(shè)置自身大小呢梁丘,
主要使用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寫(xiě)法
//
// 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)
}
}