第一,而不是给予高度来看,你应该给标签的高度
class ViewController : UITableViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 40
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 4
}
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
cell.backgroundColor = UIColor.yellow
cell.textLabel?.text = "Baran"
return cell
}
override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat
{
return heightForView()
}
override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let headerView : UIView = UIView(frame: CGRect(x: 0, y: 20, width: self.view.frame.width, height: self.heightForView()))
headerView.backgroundColor = UIColor.black
let label : UILabel = UILabel(frame: CGRect(x: 0, y: 0, width: self.view.frame.width, height: self.heightForView()))
label.numberOfLines = 0
label.textAlignment = NSTextAlignment.center
label.text = "Size To Fit Tutorial"
label.font = UIFont(name: "Helvetica", size: 50)
label.textColor = UIColor.white
headerView.addSubview(label)
return headerView
}
//Self Sizing height ....
func heightForLabel(text:String, font:UIFont, width:CGFloat) -> CGFloat{
let label:UILabel = UILabel(frame: CGRect(x: 0, y: 0, width: width, height: CGFloat.greatestFiniteMagnitude))
label.numberOfLines = 0
label.lineBreakMode = NSLineBreakMode.byCharWrapping
label.font = font
label.text = text
label.sizeToFit()
return label.frame.height
}
func heightForView() -> CGFloat{
let screenSize = UIScreen.main.bounds
let screenWidth = screenSize.width
let text = "Size To Fit Tutorial"
let font : UIFont!
switch UIDevice.current.userInterfaceIdiom {
case .pad:
font = UIFont(name: "Helvetica", size: 35)
case .phone:
font = UIFont(name: "Helvetica", size: 50)
default:
font = UIFont(name: "Helvetica", size: 24)
}
let height = heightForLabel(text: text, font: font, width: screenWidth)
return height
}
}
enter image description here
希望这有助于
你试过FUNC的tableView(UITableView的,heightForHeaderInSection:智力)中的UITableViewDelegate? – RinaLiu
您的意思是它使用动态类型作为Apple技术(例如UIFontTextStyle),或者您的意思是它们只是具有不同的字体大小? – Alistra
@Alistra,我的意思是苹果定义它的动态类型 - 'storyboard'中使用的UIFontTextStyle。当应用程序运行时,我想从可访问性更改字体,并且我希望相应地更改tableHeader的高度,以使文本可见 –