具有锚样式自动布局约束的 UIButtons 未显示
Posted
技术标签:
【中文标题】具有锚样式自动布局约束的 UIButtons 未显示【英文标题】:UIButtons with anchor style auto layout constraints not showing 【发布时间】:2015-10-14 16:53:30 【问题描述】:我以这种方式添加了一个子视图:
dailyButtonView.translatesAutoresizingMaskIntoConstraints = false
dailyButtonView.backgroundColor = UIColor.redColor()
dailyWeeklyButtonViewContainer.addSubview(dailyButtonView)
let centerX_d = dailyButtonView.centerXAnchor.constraintEqualToAnchor(dailyWeeklyButtonViewContainer.centerXAnchor)
let centerY_d = dailyButtonView.centerYAnchor.constraintEqualToAnchor(dailyWeeklyButtonViewContainer.centerYAnchor)
let width_d = dailyButtonView.widthAnchor.constraintEqualToAnchor(dailyWeeklyButtonViewContainer.widthAnchor)
let height_d = dailyButtonView.heightAnchor.constraintEqualToAnchor(dailyWeeklyButtonViewContainer.heightAnchor)
dailyButtonViewCenterX = centerX_d
NSLayoutConstraint.activateConstraints([centerX_d,centerY_d,width_d,height_d])
紧接着,我想添加六个UIButton
(大小相同且间距相等),所以我这样做了:
let dayButtonSide = self.dailyButtonView.frame.height * 0.6
let dayDistance = (self.dailyButtonView.frame.width - dayButtonSide * 7) / 8.0
for index in 0...6
let temp = UIButton()
temp.translatesAutoresizingMaskIntoConstraints = false
temp.layer.cornerRadius = 5
dailyButtonView.addSubview(temp)
var test = CGFloat(index) * (dayButtonSide / 2)
test += CGFloat(index + 1) * dayDistance - (dailyButtonView.bounds.width / 2)
let centerX_t = temp.centerXAnchor.constraintEqualToAnchor(dailyButtonView.centerXAnchor, constant: test)
let centerY_t = temp.centerYAnchor.constraintEqualToAnchor(dailyButtonView.centerYAnchor)
let width_t = temp.widthAnchor.constraintEqualToAnchor(nil, constant: dayButtonSide)
let height_t = temp.heightAnchor.constraintEqualToAnchor(nil, constant: dayButtonSide)
NSLayoutConstraint.activateConstraints([centerX_t, centerY_t, width_t, height_t])
但是,即使日志中没有错误或警告,按钮也不会在模拟中显示。
【问题讨论】:
【参考方案1】:我想通了。问题在于这一行:let dayButtonSide = self.dailyButtonView.frame.height * 0.6
。因为我在viewDidLoad
中调用了这个函数,所以dailyButtonView
没有在这一点上列出。
【讨论】:
以上是关于具有锚样式自动布局约束的 UIButtons 未显示的主要内容,如果未能解决你的问题,请参考以下文章