我已将自定义图像添加到我的UITableView标题部分。当屏幕处于纵向模式时,它正常工作。横向模式中出现较大间隙。任何人都可以帮助我吗?
override func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
var headerView = UIView(frame: CGRect(x: 1, y: 1, width: tableView.frame.width, height: 40))
var myLabel = UILabel()
myLabel.frame = CGRectMake(0, 0, tableView.frame.width - 70, 40)
print(myLabel.frame)
myLabel.font = UIFont.boldSystemFontOfSize(18)
myLabel.backgroundColor = UIColor.blueColor()
myLabel.text = self.tableView(tableView, titleForHeaderInSection: section)
let button = UIButton(frame: CGRect(x: 230,y: 0,width: 100,height: 40))
button.tag = section
button.backgroundColor = UIColor.clearColor()
headerView.addSubview(button)
headerView.addSubview(myLabel)
headerView.backgroundColor = UIColor.clearColor()
// the button is image - set image
button.setImage(UIImage(named: "icoDraft"), forState: UIControlState.Normal)
let tapOnCardCell: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(HHLabTestExaminationViewController.handleTapOnSectionImage(_:)))
button.addGestureRecognizer(tapOnCardCell)
return headerView
}
现在标题部分的标题是
override func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
if(section == 0)
{
return "Exam"
}
else if(section == 1)
{
return "News"
}
else if(section == 2)
{
return "Movie"
}
else if(section == 3)
{
return "Sport"
}
return ""
}
答案 0 :(得分:2)
设置此标题视图时,我看不到任何自动布局代码。但是,可以在没有自动布局的情况下处理这种简单的布局。
headerView.autoResizesSubviews = true
myLabel.autoResizingMask = [.flexibleWidth, .flexibleHeight]
button.autoResizingMask = .flexibleLeftMargin
答案 1 :(得分:1)
正如@DaveWeston所说,没有自动布局代码,他的答案应该可以正常工作。如果你想要自动布局,这就是按钮的样子。
(注意这是OP代码中的Swift 3 vs. 2.x)。
let button = UIButton()
button.tag = section
button.backgroundColor = UIColor.clear
headerView.addSubview(button)
// Autolayout for button
button.translatesAutoresizingMaskIntoConstraints = false
button.addConstraint(NSLayoutConstraint.init(item: button,
attribute: .height,
relatedBy: .equal,
toItem: headerView,
attribute: .height,
multiplier: 1.0,
constant: 0.0))
button.addConstraint(NSLayoutConstraint.init(item: button,
attribute: .width,
relatedBy: .equal,
toItem: nil,
attribute: .width,
multiplier: 1.0,
constant: 40.0))
button.addConstraint(NSLayoutConstraint.init(item: button,
attribute: .trailing,
relatedBy: .equal,
toItem: headerView,
attribute: .trailing,
multiplier: 1.0,
constant: 0.0))
button.addConstraint(NSLayoutConstraint.init(item: button,
attribute: .centerY,
relatedBy: .equal,
toItem: headerView,
attribute: .centerY,
multiplier: 1.0,
constant: 0.0))