在 viewDidLoad()
方法中,我想创建 10 个 UIButton,给它们添加标题
[“一”、“二”、“三”、“四”、“五”、“六”、“七”、“八”、“九”、“十”]
并将它们添加到 View 中,使其始终使用约束进行响应式放置。
我想要将UIButton
添加到View
,它始终位于页面顶部,但响应设备的用户定位和放置的文本进入UIButton.title
。
这与 Bootstrap CSS 使用 CSS 类“table”、“row”、“col-md-2”所做的事情相同。
如果按钮的标题发生变化,代码应该自动调整位置,如下所示:
最佳答案
使用UICollectionView
和UICollectionViewFlowLayout
,使您的 Controller 符合UICollectionViewDelegateFlowLayout
协议(protocol),然后为每个单元格计算的宽度UIButton
,然后将大小提供给 UICollectionViewDelegateFlowLayout
类似于:
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let itemWidth = ...//calculate the width of the button
return CGSize(width: kCGImagePropertyIPTCExtMaxAvailWidth, height: 50)//set height to whatever you want
}
关于ios - swift iOS : Programmatically create a responsive menu using UIButton and a View and constraints,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50117579/