ios - UIButton 以相等的宽度快速延伸超过 UIView 的边缘

标签 ios swift uibutton

我在将以编程方式创建的 UIButton 保持在 UIView 的范围内时遇到了一些问题。

界面的构建方式如下: ScrollView -> ContentView -> (从 SQLite 循环以编程方式创建的按钮列表)

这是创建按钮的代码;

            let frame = CGRect(x: 0, y: 0 + (numOfButtons * 58), width: Int(ContentView.frame.width) , height: 50 )
            let button = UIButton(frame: frame)                
            button.showsTouchWhenHighlighted=true
            button.layer.cornerRadius=5
            button.setTitle(btnTitle, for: [])
            ContentView.addSubview(button)
            numOfButtons+=1
            button.addTarget(self, action: #selector(btnPressed), for: .touchUpInside)
<小时/>

这段代码给出了这个结果;

Picture of button

有人对我如何解决这个问题有任何想法吗?在我看来,ContentView 太宽了?但我将其设置为与 ScrollView 等宽。

任何和所有的帮助将不胜感激。 提前致谢

克里斯。

最佳答案

请检查我的以下代码以供引用

这是我的代码输出

Output

import UIKit

class ViewController: UIViewController,UIScrollViewDelegate {


@IBOutlet weak var ContentView: UIView!

var scrollView: UIScrollView!
var containerView = UIView()


override func viewDidLoad() {
    super.viewDidLoad()


    let button   = UIButton(type: UIButtonType.custom) as UIButton

    let image = UIImage(named: "image") as UIImage?
    let frame = CGRect(x: 20, y: 300, width: self.view.frame.size.width - 20 - 20, height: 50 )
    button.frame = frame
    button.showsTouchWhenHighlighted=true
    button.layer.cornerRadius=5
    button.clipsToBounds=true
    button.setBackgroundImage(image, for: .normal)
    button.setTitle("Hi", for:.normal)

    self.scrollView = UIScrollView()
    self.scrollView.delegate = self
    self.scrollView.contentSize = CGSize(width: 1000, height: 1000)


    containerView = UIView()


    scrollView.addSubview(containerView)
    view.addSubview(scrollView)
    self.view.addSubview(button)


}

override func viewDidLayoutSubviews() {
    super.viewDidLayoutSubviews()

    scrollView.frame = view.bounds
    containerView.frame = CGRect(x: 0, y: 0, width: scrollView.contentSize.width, height: scrollView.contentSize.height)


}

关于ios - UIButton 以相等的宽度快速延伸超过 UIView 的边缘,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45024873/

相关文章:

security - iPhone应用程序和安全性?

ios - 将按钮连接到导航 View Controller

swift - AppDelegate 不显示 Storyboard 按钮

swift - 如何从 NSObject 访问多个按钮?

ios - 在我的 mapView 上添加注释后设置坐标更新

ios - 如何处理网络中间请求的变化 - Alamofire

ios - adjustsFontSizeToFitWidth 在 iOS 14 上与 NSMutableAttributedString 无法正常工作

swift - Swift 中的 TimSort

ios - 点击时选择/取消选择 UIButton