【问题标题】:Why does UIButton.setTitle change the font size?为什么 UIButton.setTitle 会改变字体大小?
【发布时间】:2021-12-20 11:14:48
【问题描述】:

我正在为一个班级构建一个 iOS 应用程序,并且我正在按照一些说明进行操作。编辑按钮连接到toggleEditingMode,但是当我更改文本时,由于某种原因字体大小被重置为17,即使它在故事板编辑器中是30。

我尝试过更改字体大小,如果我在执行 setTitle 后打印当前字体大小,它仍然显示 30,所以它似乎必须在 setTitle 之外发生,但它只有在我使用 setTitle 时才会触发。救命!

class ItemsViewController: UITableViewController {
    var choreStore: ChoreStore!
    var roommateStore: RoommateStore!
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return choreStore.allChores.count
    }
        
    override func tableView(_ tableView: UITableView,
            cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        // Create an instance of UITableViewCell with default appearance
        let cell = tableView.dequeueReusableCell(withIdentifier: "chore", for: indexPath) as! ChoreCell

        // Set the text on the cell with the description of the item
        // that is at the nth index of items, where n = row this cell
        // will appear in on the table view
        let chore = choreStore.allChores[indexPath.row]

        cell.title?.text = chore.title
        cell.turn?.text = "\(chore.whoseTurn())'s Turn"
        cell.completed?.text = chore.completedString()
        cell.completed?.textColor = chore.isOverdue ? .red : .black

        return cell
    }
    
    @IBAction func addNewItem(_ sender: UIButton) {

    }

    @IBAction func toggleEditingMode(_ sender: UIButton) {
        setEditing(!isEditing, animated: true)
        sender.setTitle(isEditing ? "Done" : "Edit", for: .normal)
    }
}

【问题讨论】:

  • 我也有同样的问题。你能解决吗?

标签: ios swift xcode


【解决方案1】:

将按钮样式更改为默认:

【讨论】:

    【解决方案2】:

    您的问题相对含糊,但根据我的解释,这应该可以解决您的字体大小问题。我还没有阅读这方面的文档,但我的猜测是,每当您使用 .setTitle 时,它​​都会创建一个全新的 UILabel,因此故事板中设置的所有属性都不再使用,因为您已经处理了原始标签。

    @IBAction func toggleEditingMode(_ sender: UIButton) {
            setEditing(!isEditing, animated: true)
            sender.setTitle(isEditing ? "Done" : "Edit", for: .normal)
            //Set the font size after setting title
            sender.titleLabel?.font = UIFont.systemFont(ofSize: 30.0) 
    
        }
    

    对于自定义字体:

    @IBAction func toggleEditingMode(_ sender: UIButton) {
            setEditing(!isEditing, animated: true)
            sender.setTitle(isEditing ? "Done" : "Edit", for: .normal)
            //Set the font size after setting title
            sender.titleLabel?.font = UIFont(name:"fontname", size: 30.0) 
    
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-03-29
      • 1970-01-01
      • 2011-12-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多